Home > database >  How to improve attach bulk Laravel?
How to improve attach bulk Laravel?

Time:11-09

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?

CodePudding user response:

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