【问题标题】:Laravel Eloquent GroupBy throwing SQL errorLaravel Eloquent Group通过抛出 SQL 错误
【发布时间】:2019-09-23 05:53:33
【问题描述】:

当我手动运行以下 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]:语法错误或访问冲突:1055 'link_checker.crawl_results.id' 不在 GROUP BY 中(SQL: select * from crawl_results 其中user_id = 1 和website_id = 1 和 item_state != OK group by destination_url limit 30 offset 0)

不确定抽象背后发生了什么导致该错误?

【问题讨论】:

  • 您能否记录从您的 eloquent 查询中生成的原始查询?
  • 我相信原始查询在它抛出的错误中?
  • 您可以直接在您的 phpmyadmin 中运行查询,然后如果您收到错误,将表前缀添加到按列名分组并告诉我结果吗?

标签: php laravel laravel-5 eloquent laravel-query-builder


【解决方案1】:

您应该转到 config\database.php 并将 strict 更改为 false

'mysql' => [
   ...
   'strict' => false,
   ...
 ]

【讨论】:

  • 这会导致其他安全问题。
【解决方案2】:

将您的查询更改为查询构建器查询

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 在分页中无法高效执行

目前,使用 groupBy 语句的分页操作不能 由 Laravel 高效执行。如果您需要使用 groupBy 与 分页结果集,建议查询数据库 并手动创建分页器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多