我有这些表:
Orders:
id - status -user_id - address_id
1 await 1 1
products:
id - name - price - quantity
1 test1 100$ 5
2 test2 50$ 5
order_product:
order_id - product_id - quantity
1 1 2
1 2 2
cities:
id - name - shipping_charges
1 NY 30$
我如何计算这些列的总价:
对于每种产品:
products(price) * order_product(quantity)
适用于所有含运费的产品
- products(price) * order_product(quantity) + cities(shipping_charges)
您可以通过访问属性来检索数据透视表列,该pivot
属性已经存在了很长时间了。
默认情况下,只有模型关键点会出现在枢轴对象上。如果数据透视表包含额外的属性,则在定义关系时必须指定它们:
在您的情况下,您可以像下面的代码中那样定义关系:
class Order extends Model {
public function products()
{
return $this->belongsToMany(Order::class)->withPivot('quantity')
}
}
现在,可以通过属性(例如)访问表quantity
上的列。order_product
pivot
$order->products()->first()->pivot->quantity
最后,这是计算订单总数的结果代码:
$total = 0;
foreach ($product as $products) {
$total += $product->price * $product->pivot->quantity
}
$total += $order->address()->city->shipping_charges
资料来源:https : //laravel.com/docs/master/eloquent-relationships#many-to-many
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句