Group by Laravel?

拜拜、爱过 提交于 2019-12-23 03:44:06

问题


I have the following query:

$orders = Order::where(function ($query) use ($request) {

            // Filter by in process delivery
            if ($request->get("status") && $request->get("status") == "2") {
                $query->where('status', "2");
            }

        })->groupBy('created_at')->get();

When I try to execute this query I get an error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'delivery.order.id' isn't in GROUP BY (SQL: select * from `order` group by `created_at`)

What is problem?


回答1:


In your config/database.php file, change mysql configuration array

from 'strict' => true

to 'strict' => false

For more information about this error read this answer.




回答2:


The problem is the final query select * from `order` group by `created_at`. It's trying to select every column, but its grouping only one. Your database is working in only full group mode which means all selected fields have to be in group by clause (or have to be aggregator functions like SUM, COUNT etc.)

I don't know what you really want to get from this query but you can select columns manually like this:

$orders = Order::where(function ($query) use ($request) {
    if ($request->get("status") && $request->get("status") == "2") {
        $query->where('status', "2");
    }
})->groupBy('created_at')
  //select columns like this
  ->select(\DB::raw('COUNT(*)'), 'created_at')
  ->get();

Another option is to disable full group mode but the result will be unexpected and probably that's not what you want.



来源:https://stackoverflow.com/questions/41199800/group-by-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!