【问题标题】:How to count the total price of order?如何计算订单总价?
【发布时间】:2020-05-17 13:51:16
【问题描述】:

我有这些表:

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)  

对于所有带有 shipping_charges 的产品

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

【问题讨论】:

  • address_id 连接到城市?
  • @TsaiKoga 是的
  • 所以如果一个产品[$20] 有两个订单,[qty: 1, qty: 2,] 两个订单有相同的城市shipping_charges[$1, $1]。所以你想调用一个产品的 shipping_charges 是20*(1+2) + 1 还是20*(1+2) + 2*1

标签: php mysql sql laravel eloquent


【解决方案1】:

通过使用 laravel 集合通过执行类似的操作来查找字段的总和;

$profuctTotal=Product::all()->sum('price'); 对使用 Eloquent 模型的其他人也这样做。

【讨论】:

  • 数据透视表的问题有模型,我该如何处理!
  • 现在我有了这个($order->products->sum('price') 没关系,但是我怎么能用我拥有的数据透视表来*这个
【解决方案2】:

您可以通过访问pivot 属性来检索pivot 表列,这是long while 的存在。

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

在您的情况下,您可以定义如下代码中的关系:

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

现在可以通过pivot 属性(例如$order->products()->first()->pivot->quantity)访问order_product 表上的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

【讨论】:

    【解决方案3】:
    • 如果您不使用任何模型,请使用此原始查询

    $orderitem = DB::table('order_product')->where('order_id', '你的订单id')->get();

        // 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 2016-08-15
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2014-03-29
      相关资源
      最近更新 更多