如何计算订单总价? [英] How to count the total price of order?

查看:83
本文介绍了如何计算订单总价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些表:

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$

如何计算这些列的总价:

How can I count the total price of the these columns:

每种产品:

  products(price) * order_product(quantity)  

对于所有具有运费的产品

for all products with shipping_charges

- products(price) * order_product(quantity) + cities(shipping_charges) 

推荐答案

您可以通过访问pivot属性来检索 pivot 表列,对于

You can retrieve the pivot table columns by accessing the pivot attribute, this has been there for a long while.

默认情况下,只有模型关键点会出现在枢轴对象上.如果数据透视表包含额外的属性,则在定义关系时必须指定它们:

By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

根据您的情况,您可以像下面的代码中那样定义关系:

In your case you can define the relationship like in the following code:

class Order extends Model {
    public function products()
    {
        return $this->belongsToMany(Order::class)->withPivot('quantity')
    }
}

现在,可以通过pivot属性(例如$order->products()->first()->pivot->quantity)访问order_product表上的quantity列.

Now the quantity column on the order_product table will be accessible via the pivot attribute (e.g. $order->products()->first()->pivot->quantity).

最后,这是计算订单总数的结果代码:

In the end, here is the resulting code to calculate the order total:

$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

这篇关于如何计算订单总价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆