Php 如何计算订单的总价?
我有这些桌子:Php 如何计算订单的总价?,php,mysql,sql,laravel,eloquent,Php,Mysql,Sql,Laravel,Eloquent,我有这些桌子: 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
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)
通过使用laravel集合查找字段的和,方法如下: $PROFACTTOTAL=Product::all()->总和(“价格”);
使用雄辩的模型为其他人做同样的事情。通过使用laravel集合,通过这样做,找到字段的总和 $PROFACTTOTAL=Product::all()->总和(“价格”); 对使用雄辩模型的其他人也要这样做。您可以通过访问
pivot
属性来检索pivot表列,这已经有一段时间了
默认情况下,轴对象上将仅显示模型关键点。如果透视表包含额外属性,则必须在定义关系时指定这些属性:
在您的情况下,您可以像以下代码中那样定义关系:
类顺序扩展模型{
公共功能产品()
{
返回$this->belongsToMany(Order::class)->withPivot('quantity')
}
}
现在,order\u product
表上的quantity
列将通过pivot
属性(例如,$order->products()->first()->pivot->quantity
)进行访问
最后,以下是计算订单总额的结果代码:
$total=0;
foreach($product as$products){
$total+=$product->price*$product->pivot->quantity
}
$total+=$order->address()->city->shipping\u费用
资料来源:
您可以通过访问pivot
属性来检索pivot表列,这已经存在了一段时间了
默认情况下,轴对象上将仅显示模型关键点。如果透视表包含额外属性,则必须在定义关系时指定这些属性:
在您的情况下,您可以像以下代码中那样定义关系:
类顺序扩展模型{
公共功能产品()
{
返回$this->belongsToMany(Order::class)->withPivot('quantity')
}
}
现在,order\u product
表上的quantity
列将通过pivot
属性(例如,$order->products()->first()->pivot->quantity
)进行访问
最后,以下是计算订单总额的结果代码:
$total=0;
foreach($product as$products){
$total+=$product->price*$product->pivot->quantity
}
$total+=$order->address()->city->shipping\u费用
资料来源:
- 如果不使用任何模型,则使用此原始查询
- 如果不使用任何模型,则使用此原始查询
pivot表的问题是它的模型我如何处理它!现在我有($order->products->sum('price')这没关系,但是我怎么能*这个数据透视表呢我有数据透视表的问题,有它的模型我怎么能处理它!现在我有了($order->products->sum('price'))没关系,但是我如何*我有
address\u id
的数据透视表连接到城市?@TsaiKoga是的,如果一个产品[$20]有两个订单,[qty:1,qty:2,]两个订单有相同的城市,shipping\u charges
[$1,1]。那么你想计算一个产品的运费是20*(1+2)+1
还是20*(1+2)+2*1
?address\u id
连接到城市?@TsaiKoga是的,如果一个产品[$20]有两个订单,[qty:1,qty:2,]两个订单有相同的城市,运费
[$1,$1]。那么你想计算一个产品的运费是20*(1+2)+1
还是20*(1+2)+2*1
?
// Now create a foreach loop for get total price
$total = 0;
foreach($orderitem as $order){
$porduct = DB::table('products')->where('id', $order->product_id)->first();
$total += $porduct->price * $order->quantity;
}
// now you got sub total
$shipping = DB::table('cities')->where('id', 'Orders table address column')->first();
$subtotal = $tatal + $shipping->shipping_charges;