Search code examples
laraveleloquenthas-many-throughhas-many

Laravel save HasMany realtion


I have a set that has a list of group and each group has a list of attributes like this

//sets
Schema::create('sets', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});

//groups
Schema::create('groups', function (Blueprint $table) {
    $table->id();         
    $table->string('name');
    $table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
});

//attributes
Schema::create('attributes', function (Blueprint $table) {
    $table->id();         
    $table->string('name');
});

//set_group_attributes
Schema::create('set_group_attributes', function (Blueprint $table) {
    $table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
    $table->foreignId('group_id')->constrained('groups')->onDelete('cascade');
    $table->foreignId('attribute_id')->constrained('attributes')->onDelete('cascade');
    $table->integer('position');
    $table->unique(['set_id', 'attribute_id']);
});

I need to save the set with groups and attributes, this is my code :

$set = Set::create(['name' => $request->name]); ---> save the set
$set->groups()->createMany($request->groups); ---> save the group

//set model
public function groups(): HasMany
{
  return $this->hasMany(Group::class, 'set_id','id');
}

My question is how to save the attributes with laravel eloquent?


Solution

  • Here we can use attach like in Docs with belongsToMany

    //group model
    /**
     * @return BelongsToMany
     */
    public function attributes(): BelongsToMany
    {
        return $this->belongsToMany(Attribute::class, 'set_group_attributes', 'group_id', 'attribute_id')->withPivot('position');
    }
    
    // save attributes of groups
    foreach ($attributes as $attribute) {
        $group->attributes()->attach($attribute['id'], ['set_id' => $model->id, 'position' => $attribute['position']]);
    }