简体   繁体   English

Laravel GroupBy数据库查询生成器不起作用

[英]Laravel groupBy Database query Builder not working

I have this problem in a query using laravel groupBy, it simply return a groupBy error. 我在使用laravel groupBy的查询中遇到此问题,它只是返回了groupBy错误。 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. 我还读了同样的问题,指出是由于postgreSQL,我需要在grouBy子句中包括所有列。 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 查询表 在此处输入图片说明

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")

There you have it add group by "purchases.id" or restrict the select to only the operates that are needed. 在那里,您可以按“ purchases.id”添加组,或者将选择限制为仅需要的操作。

->select("purchase_order_id","purchases.id")

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

Agreggates for your case should mean something like ->select("sum(po_total)") 针对您的案例的Agreggates应该表示类似->select("sum(po_total)")


If we group by id, we get all results as id is unique, my mistake. 如果我们按ID分组,我们会得到所有结果,因为ID是唯一的,这是我的错。 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 经验法则是您要么使用Sum()选择一个字段,要么将其放在分组依据

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

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