Laravel Eloquent GroupBy 抛出 SQL 错误
Laravel Eloquent GroupBy throwing SQL error
当我手动 运行 以下 SQL 时,我得到了预期的结果,没有错误
select * from `crawl_results`
where `user_id` = 1 and `website_id` = 1
and `item_state` != 'OK' group by `destination_url`
limit 30 offset 0
但是当我 运行 这个在 Eloquent...
self::where('user_id', Auth::id())
->where('website_id', $scanID)
->where('item_state', '!=' , 'OK')
->groupby('destination_url')->paginate(30)
它产生这个错误:
SQLSTATE[42000]: Syntax error or access violation: 1055
'link_checker.crawl_results.id' isn't in GROUP BY (SQL: select * from
crawl_results
where user_id
= 1 and website_id
= 1 and
item_state
!= OK group by destination_url
limit 30 offset 0)
不确定产生该错误的抽象背后发生了什么?
您应该转到 config\database.php 并将 strict 更改为 false
'mysql' => [
...
'strict' => false,
...
]
将您的查询更改为查询构建器查询
DB::table('crawl_results')->where('user_id', Auth::id())->where('website_id', $scanID)->where('item_state', '!=' , 'OK')->groupby('destination_url')->paginate(30);
它应该可以正常工作。
documentation中提到分页时GROUP BY不能高效执行
Currently, pagination operations that use a groupBy statement cannot
be executed efficiently by Laravel. If you need to use a groupBy with
a paginated result set, it is recommended that you query the database
and create a paginator manually.
当我手动 运行 以下 SQL 时,我得到了预期的结果,没有错误
select * from `crawl_results`
where `user_id` = 1 and `website_id` = 1
and `item_state` != 'OK' group by `destination_url`
limit 30 offset 0
但是当我 运行 这个在 Eloquent...
self::where('user_id', Auth::id())
->where('website_id', $scanID)
->where('item_state', '!=' , 'OK')
->groupby('destination_url')->paginate(30)
它产生这个错误:
SQLSTATE[42000]: Syntax error or access violation: 1055 'link_checker.crawl_results.id' isn't in GROUP BY (SQL: select * from
crawl_results
whereuser_id
= 1 andwebsite_id
= 1 anditem_state
!= OK group bydestination_url
limit 30 offset 0)
不确定产生该错误的抽象背后发生了什么?
您应该转到 config\database.php 并将 strict 更改为 false
'mysql' => [
...
'strict' => false,
...
]
将您的查询更改为查询构建器查询
DB::table('crawl_results')->where('user_id', Auth::id())->where('website_id', $scanID)->where('item_state', '!=' , 'OK')->groupby('destination_url')->paginate(30);
它应该可以正常工作。
documentation中提到分页时GROUP BY不能高效执行
Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.