我在使用laravel groupBy的查询中遇到此问题,它只返回groupBy错误。我已经阅读了有关这方面的文档,但无法弄明白。我也读到同样的问题,指出由于postgreSQL我需要包含grouBy子句中的所有列。我尝试了但仍然没有返回明确的值。请帮我解决一下这个。以下是我的代码。非常感谢。
控制器功能
public function index(){
$purchases = Purchase::groupBy('purchase_order_id')->get();
return view('purchases/purchases_crud', ['allPurchases' => $purchases]);
}
错误
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")
答案 0 :(得分:1)
您可以通过“purchases.id”添加组,或将select限制为仅需要的操作。
->select("purchase_order_id","purchases.id")
->groupBy("purchases.id") // add if possible
对于您的案例,Agreggates应该是->select("sum(po_total)")
如果按ID分组,我们会得到所有结果,因为id是唯一的,我的错误。你想要这样的东西
DB::table("purchases")->select("purchase_order_id", DB:raw("sum(po_total)"))->groupBy("purchase_order_id")->get();
经验法则是您选择带有Sum()的字段,或者通过
将其放在组中