2

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?

3
  • Did you check the docs? The answer is explained there...
    – Gert B.
    Commented Jan 5, 2023 at 12:28
  • what do you suggest like relation ?
    – GAOUL
    Commented Jan 5, 2023 at 12:44
  • is a bit difficult because here we have 3 foreignKey to use manyToMany
    – GAOUL
    Commented Jan 5, 2023 at 12:51

1 Answer 1

1

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']]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.