Kenjie
Kenjie

Reputation: 1

Laravel 9 Eloquent Sum of relation's column

This is my very first question. And hope someone can help me.

I am trying to get all orders with there corresponding total amount of order items. And I manage to get the amount per order items.

How to return also in my select query the sum of amount per Order ?

    $orders = Order::join('user_category', 'user_category.user_id', '=', 'orders.purchaser_id')
      ->join('users', 'users.id', '=', 'user_category.user_id')
      ->with([
        'orderItems' => function($query) {
          $query->join('orders', 'orders.id', '=', 'order_items.order_id')->join('products', 'products.id', '=', 'order_items.product_id')
          ->select('order_items.order_id','order_items.quantity', 'products.price', DB::raw('order_items.quantity * products.price AS amount'));
        }
      ])
      ->select('orders.id', 'users.first_name', 'users.last_name')
      ->where('user_category.category_id', '=', 1)
      ->orderBy('orders.id', 'DESC')
      ->limit(5)
      ->get();

Upvotes: 0

Views: 1218

Answers (1)

RossTsachev
RossTsachev

Reputation: 921

"with" is a relation, while everything else you have are joined tables. You can modify your like that:

$orders = Order::join('user_category', 'user_category.user_id', '=', 'orders.purchaser_id')
      ->join('users', 'users.id', '=', 'user_category.user_id')
      ->leftJoin('order_items', 'order_items.order_id', '=', 'orders.id')
      ->join('products', 'products.id', '=', 'order_items.product_id')
      ->select('orders.id', 'users.first_name', 'users.last_name')
      ->addSelect(DB::raw('sum(order_items.quantity * products.price) as amount'))
      ->where('user_category.category_id', '=', 1)
      ->groupBy('orders.id', 'DESC')
      ->orderBy('orders.id', 'DESC')
      ->limit(5)
      ->get();

Upvotes: 1

Related Questions