D
D
Dinesh_Chugtai2020-11-03 15:04:15
Laravel
Dinesh_Chugtai, 2020-11-03 15:04:15

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.
5fa14620ec05c151846582.png

If you first check the ID and then do detach and attach, then the request is combined into one
5fa14722110a5420907973.png

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

1 answer(s)
D
Dinesh_Chugtai, 2020-11-03
@Dinesh_Chugtai

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

And in the controller, when updating information, I pass relations and their data.
$product->sync('attributes', $request->get('attributes'));
$product->sync('categories', $request->get('categories'));
$product->sync('promotions', $request->get('promotions'));

In the $request of the links, I get all the columns, so I only need to get the id .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question