简体   繁体   English

Laravel 9 Eloquent 关系列的总和

[英]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.而且我设法获得每个订单项目的amount

How to return also in my select query the sum of amount per Order ?如何在我的 select 查询中返回每个Order的总amount

    $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();

"with" is a relation, while everything else you have are joined tables. “with”是一种关系,而你拥有的其他一切都是连接表。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM