У меня есть эти таблицы:
Продукты:
id - name - quantity - etc
2 watch 4
4 T-shirt 2
Заказы:
id - user_id - address_id - etc
Сводная таблица между ними называется order_product
order_id - product_id - quantity
1 2 3
1 4 1
Соотношение:
/**
* Products table relation
*/
public function products()
{
return $this->belongsToMany('App\Models\Product')->withPivot('quantity');
}
/**
* Orders table relation
*/
public function orders()
{
return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
}
Мне нужно, когда я обновляю статус до утвержденного, затем обновляю количество товара!
Мой выход: (Здесь я запутался, потому что продукт может быть много! количество тоже)
public function status_orders(Order $order ,Request $request)
{
if($request->status == 'approved'){
$product_quantity = $order->products->pluck('quantity');
foreach($order->products as $order){
$order_quantity = $order->pivot->quantity;
}
$final_quantity = $product_quantity - $order_quantity;
}
}