Laravel更新多个相同belongsToMany关系
问题描述:
我有一个Orders
表和Products
表,我之间的关系设置为belongsToMany
关系,这工作正常。Laravel更新多个相同belongsToMany关系
但是,订单可以有多个相同的产品(如果他们想订购更多,管理员可以提供折扣)。
例如:
Order 1 has
Product 1 x 5 (£1 each = £5 total)
Product 1 x 2 (£0.75 each = £1.50 total)
如何更新单行?我曾尝试以下,但这个更新的所有行,因为它仅接受产品ID:
$order->products()->updateExistingPivot($productID, $values);
我也曾尝试以下,但wherePivot
似乎并没有产生太大的影响调用update
时方法所有的行本产品的更新
$pivotProduct = $order->products()->wherePivot('id', $pivotId)->first();
$pivotProduct->pivot->price = '0.75';
$pivotProduct->pivot->update();
答
管理通过执行来解决这个以下:
$pivotProduct = $order->products()->wherePivot('id', $pivotId)->first();
$pivotProduct->pivot->where('id', $pivotId)->update($values);
该第二升ine确保只更新具有相同pivotId的行。