How to count the total price of order?

Deadly 提交于 2020-02-16 10:02:43

问题


I have these tables:

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:

for each product:

  products(price) * order_product(quantity)  

for all products with shipping_charges

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

回答1:


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')
    }
}

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

Source: https://laravel.com/docs/master/eloquent-relationships#many-to-many




回答2:


Find the sum of a field by using laravel collection by doing something like this;

$profuctTotal=Product::all()->sum('price'); Do same for others using Eloquent models.




回答3:


  • If you don't use any model then use this raw query

$orderitem = DB::table('order_product')->where('order_id', 'your order 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;


来源:https://stackoverflow.com/questions/60011582/how-to-count-the-total-price-of-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!