doufei16736 2017-09-06 11:57
浏览 149
已采纳

Laravel连接表并获得用户的最大订单

I have 2 models Orders and Users, i want to get the list of users who ordered most with the sum of total as amount

The table structure

  //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

Tried with following query

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

Getting Following error

    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)

thank you

  • 写回答

2条回答 默认 最新

  • douxue4242 2017-09-06 12:04
    关注

    You can write this query as,

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

    As raw query, because by default it will consider whole string as column

    EDIT

    Your problem was, you were doing group by on field which is taken inside aggregate function.

    Here are some links to explain my concern much better.

    I have made changes in code. Please check once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?