How to count the total price of order?

前端 未结 3 867
梦如初夏
梦如初夏 2021-01-28 02:25

I have these tables:

Orders: 
id - status -user_id - address_id 
1     await    1          1 

products:
id -  name -   price  - quantity
1     test1    100$             


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 02:42

    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

提交回复
热议问题