Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to improve attach bulk Laravel?

I try to attach rating to the user using many to many relation:

foreach ($rating as $value) {
    $rateduser->rates()->attach($value->rateid, ['order_id' => $order->getId(), 'user_id' => $user->getId(), 'rate' => $value->rate]);
}

As you can see I try to attach rate, rateid and additional data one by one. So it is exeecuted over 5 queries at time.

Is it possible to use one bulk insert request?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

attach accept an array for mass attaching where the index is the foreign key

$toBeAttached = [];
foreach ($rating as $value) {
    $toBeAttached[$value->rateid] = ['order_id' => $order->getId(), 'user_id' => $user->getId(), 'rate' => $value->rate];
}
if ($toBeAttached) {
    $rateduser->rates()->attach($toBeAttached);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading