Search code examples
phplaravelrelationshiphas-and-belongs-to-many

Laravel update multiple of the same belongsToMany relationship


I have an Orders table and a Products table, my relationship between these is setup as a belongsToMany relationship, which works fine.

However, an Order can have the same Product multiple times (in case they want to order more and the admin can offer a discount).

For example:

Order 1 has

Product 1 x 5 (£1 each = £5 total)
Product 1 x 2 (£0.75 each = £1.50 total)

How can I update a single row? I have tried the following, but this updates all of the rows as it only accepts the product ID:

$order->products()->updateExistingPivot($productID, $values);

I have also tried the following, but the wherePivot doesn't seem to have much effect when calling the update method as all of the rows for this product are updated

$pivotProduct = $order->products()->wherePivot('id', $pivotId)->first();
$pivotProduct->pivot->price = '0.75';
$pivotProduct->pivot->update();

Solution

  • Managed to fix this by doing the following:

     $pivotProduct = $order->products()->wherePivot('id', $pivotId)->first();
     $pivotProduct->pivot->where('id', $pivotId)->update($values);
    

    This second line ensures that only the row with the same pivotId is updated.