dongni9825 2016-05-30 13:46
浏览 104
已采纳

Laravel groupBy数据库查询生成器无法正常工作

I have this problem in a query using laravel groupBy, it simply return a groupBy error. I have read the documentation about this but can't really figure it out. I also read the same problem pointing that it is because of postgreSQL that I need to include all the columns in grouBy clause. I tried it but still it doesn't return the distinct values. Please help me with this. Below is my code. Thanks a lot.

Controller function

 public function index(){
    $purchases = Purchase::groupBy('purchase_order_id')->get();
    return view('purchases/purchases_crud', ['allPurchases' => $purchases]);
}

Table to query enter image description here

Error

QueryException in Connection.php line 680:
SQLSTATE[42803]: Grouping error: 7 ERROR: column "purchases.id" must appear
in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "purchases" group by "purchase_order_id"
^ (SQL: select * from "purchases" group by "purchase_order_id")
  • 写回答

1条回答 默认 最新

  • douzai8285 2016-05-30 13:51
    关注

    There you have it add group by "purchases.id" or restrict the select to only the operates that are needed.

    ->select("purchase_order_id","purchases.id")
    
    ->groupBy("purchases.id") // add if possible
    

    Agreggates for your case should mean something like ->select("sum(po_total)")


    If we group by id, we get all results as id is unique, my mistake. You want something like this

    DB::table("purchases")->select("purchase_order_id", DB:raw("sum(po_total)"))->groupBy("purchase_order_id")->g‌​et();
    

    Rule of thumb is you either select a field with Sum() or have it on the group by

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?