1

I would like to sync the data instead of attach the data to the particular relationship.

Pivot relation UserModel code

public function carts(){
        return $this->belongsToMany(Product::class,'user_carts')->withPivot('quantity');
    }

The attach code is

User::find(1)->carts()->attach($s,["quantity"=>1]);

The sync code is

User::find(1)->carts()->sync($s,["quantity"=>1]);

When I try to compile the sync, those pivot relation that matched user_id = 1 does not have the "1" in its respective quantity column.

If I would like to achieve the sync function without using attach, how can I do it because the attach() will create multiple redundant data in my database.

Miracle Hades
  • 146
  • 2
  • 10

1 Answers1

2

You have to pass key values in the sync method. Assuming $s is the id (key) to be synced:

User::find(1)->carts()->sync([$s => ["quantity"=>1]]);
Daan
  • 12,099
  • 6
  • 34
  • 51