1

I have this two 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

Relation in Order Model:

public function products()
{
    return $this->belongsToMany('App\Models\Product')->withPivot('quantity')->withTimestamps();
}

I need this:

foreach each product then MULTIPLY the price of each product with the third table in order_product(quantity)??

My Shut:

 foreach ($order->products as $product) {

        $total_price = $product->pivot->quantity * $product->price;

  }

I need after this to sum the total price after MULTIPLY with pivot(quantity) ?

Amit Kumar PRO
  • 1,222
  • 2
  • 15
  • 27
  • 1
    Does this answer your question? [How to count the total price of order?](https://stackoverflow.com/questions/60011582/how-to-count-the-total-price-of-order) – Raed Yakoubi Feb 01 '20 at 05:18

3 Answers3

0

The orders and products' relationship are many-to-many.

Join:

You can use left join:

$product_query = Product::leftjoin('order_product', 'order_product.product_id', '=','product.id')
       ->select("product.*", DB::raw("SUM(product.price * order_product.quantity) AS total_price"));

So you can get the product with total_price:

$product_query->find(1)->total_price;

Accessor:

You can use accessor to get the attributes,

In your Product model, use withPivot to add pivot's data, and use accessor:

    protected $appends = ["total_price"];

    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_product', 'product_id', 'order_id')
                   ->withPivot('quantity') // You need to add the pivot datas here.
                  ->withTimestamps();
    }

    // Add accessor here:
    public function getTotalPriceAttribute() {
        return $this->price * $this->orders->sum('pivot.quantity');
    }

So you can get the product with total_price:

Product::first()->total_price;
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28
0

Try this,

foreach ($order->products as $product) {

        $total_price += $product->pivot->quantity * $product->price;

  }

just add += so that after multiplication it will get added to total.

Varsha Jadhav
  • 81
  • 1
  • 5
0

try this

in your model

public function orders()
{
    return $this->belongsToMany(Order::class, 'order_product', 'product_id', 'order_id')
               ->withPivot('quantity')
               ->withTimestamps();
} 

and change

$total_price = 0;

foreach ($order->products as $product) {

        $total_price += $product->pivot->quantity * $product->price;

  }
VIKAS KATARIYA
  • 5,867
  • 3
  • 17
  • 34