0

data:

id  modelable_type  modelable_id    category_id slug
7   Modules\Admin\Entities\AdminModel   10  1   admin
8   Modules\Admin\Entities\AdminModel   10  2   admin2

and code is :

//sync method:
$admin->categoriesRelation()->sync([1 => ['slug' => 'admin'], 2 => ['slug' => 'admin2']]);

admin relation:

//relation :
public function categoriesRelation(): belongsToMany {
        return $this->belongsToMany(CategoryModel::class, 'category_relations', 'modelable_id', 'category_id')->withPivot('slug')->withPivotValue('modelable_type', static::class);
}

queries:

select * from `category_relations` 
where `modelable_type` = 'Modules\Admin\Entities\AdminModel'
    and `category_relations`.`modelable_id` = 10

update `category_relations` 
set `slug` = 'admin' 
where `modelable_type` = 'Modules\Admin\Entities\AdminModel'
    and `category_relations`.`modelable_id` = 10 and `category_id` in (1)

update `category_relations` 
set `slug` = 'admin2' 
where `modelable_type` = 'Modules\Admin\Entities\AdminModel'
    and `category_relations`.`modelable_id` = 10 and `category_id` in (2)

relation sync without any data change, All records are updated again.

Stefan Wuebbe
  • 2,109
  • 5
  • 17
  • 28
  • 1
    Please post your data and queries as text within the question. See https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors – Calum Halpin Dec 31 '22 at 02:39

1 Answers1

0

The sync method will remove any existing records in the pivot table that are not part of update array, and then insert the two records you specified.

If you do not want to update the existing records in the pivot table, you can use the attach method instead.

Ali Raza
  • 842
  • 7
  • 13