Answer the question
In order to leave comments, you need to log in
Many INSERT queries when using sync, how to fix it?
When using the sync() method, many queries are created to insert and delete a row in the database. At the same time, up to 250 attributes can be added at a time. Then Eloquent will create 250 INSERT queries without merging them into one.
If you first check the ID and then do detach and attach, then the request is combined into one
Used many-to-many relationship .
The question is, is it possible to somehow achieve this with sync (), and from your point of view, is it worth fighting at all? Is this situation normal? Most likely I do not understand something.
Answer the question
In order to leave comments, you need to log in
In my case, I don’t need to bother much, so I decided to write the sync () function in the main Product model as a solution
public function sync(string $relation, array $id) {
$current_ids = $this->$relation()->allRelatedIds()->toArray();
$new_ids = array_filter(array_pluck($id, 'id'));
$this->$relation()->detach(array_diff($current_ids, $new_ids));
$this->$relation()->attach(array_diff($new_ids, $current_ids));
}
$product->sync('attributes', $request->get('attributes'));
$product->sync('categories', $request->get('categories'));
$product->sync('promotions', $request->get('promotions'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question