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

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

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

报告相同问题?