1
votes

I have a many-to-many relationship in laravel with a pivot table that joins Products and Orders with an order_product table with the pivot value of Quantity.

Now I am able create the order and add each product in a loop using this:

foreach($products as $product){
    $order->products()->save($product,["quantity" => 3]);
}

But, since I have to create entries with hundreds of products, hitting the database for every product does not seem ideal to me, so I'm trying so use this:

$order->products()->saveMany([$product1,$product2,$product3]);

My question is: How, in the second example, using saveMany, can I set the pivot value quantity for each product?

1

1 Answers

3
votes

You should use attach instead. saveMany is for one-to-many relation which doesn't have pivot table. If you have pivot table it's many-to-many relation. Then the code looks like that:

$data = [];
foreach ($products as $product) {
   $data[$product->id] = ['quantity' => 3];
}
$order->products()->attach($data);

Documentation: https://laravel.com/docs/5.5/eloquent-relationships