Laravel 加入表格并获得用户的最大订单

Laravel join tables and get max orders by users

我有 2 个型号 OrdersUsers,我想获得订购最多的用户列表 总计 的总和为 数量

table结构

  //users
    id  name  phone_number  
    1   John  1111111111
    2   Mike  2222222222

  //orders
    id  user_id  total 
    1     1      500  
    2     1      450
    3     2      560
    4     1      850
    5     2      500

  //expected result 
    name  phone_number  orders  amount 
    John  1111111111      3      1800
    Mike  2222222222      2      1060

尝试了以下查询

$privilaged_users = User::leftJoin('orders', 'orders.user_id', 'users.id')
                        ->select('name','phone_number')
                        ->max('orders.user_id as orders')
                        ->groupBy('orders.user_id')
                        ->get();

出现跟随错误

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in
 your SQL syntax; check the manual that corresponds to your MySQL server version
 for the right syntax to use near 'as `orders`) as aggregate from `users` left 
join `orders` on `orders`.`user_id` ' at line 1 (SQL: select 
max(`orders`.`user_id` as `orders`) as aggregate from `users` left join `orders`
 on `orders`.`user_id` = `users`.`id` where `users`.`deleted_at` is null)

谢谢

SELECT MAX(field AS something) 是无效语法。试试这个:

$privilaged_users = User::leftJoin('orders', 'orders.user_id', 'users.id')
                        ->select('name','phone_number', DB::raw('max(orders.user_id) AS orders_total'), 'orders.user_id')
                        ->groupBy('orders.user_id')
                        ->get();

并将 MAX 字段引用为 "aggregate"

您可以将此查询写为,

$privilaged_users = User::leftJoin('orders', 'orders.user_id',"=", 'users.id')
                    ->select('name','phone_number',DB::raw('max(orders.total) as orders_total'))
                    ->groupBy('orders.user_id')  
                    ->get();

作为原始查询,因为默认情况下它将整个字符串视为列

编辑

你的问题是,你正在对聚合函数内部的字段进行分组。

这里有一些链接可以解释

我修改了代码。请检查一次。