Laravel更新了同一belongsToMany关系的多个

时间:2017-06-21 07:32:11

标签: php laravel relationship has-and-belongs-to-many

我有一个function RandomUnique(){ var charBank = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789"; var random= ''; var howmanycharacters = 8; for (var i = 0; i < howmanycharacters ; i++) { random+= charBank[parseInt(Math.random() * charBank.lenght)]; } return random; } var random = RandomUnique(); console.log(random); 表和一个Orders表,我之间的关系设置为Products关系,效果很好。

但是,订单可以多次拥有相同的产品(如果他们想要订购更多产品并且管理员可以提供折扣)。

例如:

belongsToMany

如何更新单行?我尝试了以下操作,但这会更新所有行,因为它只接受产品ID:

Order 1 has

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

我也尝试过以下操作,但调用$order->products()->updateExistingPivot($productID, $values); 方法时wherePivot似乎没有太大作用,因为此产品的所有行都已更新

update

1 个答案:

答案 0 :(得分:0)

通过执行以下操作来管理解决此问题:

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

第二行确保只更新具有相同pivotId的行。