我正在尝试在laravel 5.3中执行一些原始查询。查询很简单,但我得到错误。
table name: users
columns: id|name|email|phone|created_at|updated_at
我的疑问:
SELECT created_at AS member_since, count(*) as row_count
FROM users
GROUP by MONTH(created_at);
当我在phpmyadmin上执行此查询时,此原始查询正常工作。但是当我使用laravel的数据库查询构建器执行此操作时,我会收到错误。
SQLSTATE[42000]: Syntax error or access violation: 1055
'query.users.created_at' isn't in GROUP BY
SQLSTATE[42000]: Syntax error or access violation: 1055
'query.users.created_at' isn't in GROUP BY (SQL: select created_at AS
member_since from `users` group by MONTH(created_at))
这是我的控制器:
$users = DB::table('users')
->select(DB::raw('created_at AS member_since', 'count(*) AS row_count'))
->groupBy(DB::raw('MONTH(created_at)'))
->get();
return response()->json($users);
如果我错了,请纠正我。有没有更好的方法来执行原始查询?
答案 0 :(得分:0)
首先,您需要了解您所获得的错误。这个问题就是https://stackoverflow.com/a/38551525/2474872
现在,考虑到这一点,你有两个选择
only_full_group_by
设置。 按照提供的指示进行操作 通过错误消息:
$users = DB::table('users')
->select(DB::raw('created_at AS member_since, count(*) AS row_count'))
->groupBy(DB::raw('MONTH(created_at)'), 'created_at')
->get();
groupBy(DB::raw('MONTH(created_at)'), 'created_at')
也可以是groupBy(DB::raw('MONTH(created_at), created_at')