【问题标题】:Laravel query builder group by error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated columnLaravel 查询生成器分组错误:SELECT 列表的表达式 #1 不在 GROUP BY 子句中并且包含非聚合列
【发布时间】:2019-02-05 14:45:17
【问题描述】:

我正在建立一个论坛。我有两个模型:线程和报告。

一个话题可以被不同的用户多次报告。

我正在制作一个页面来显示已向版主报告的主题。

现在的问题是,我将按线程对报告进行分组,以便显示单个线程被报告了多少次,并且如果多次报告同一线程就不会出现多次。

报告表:

$table->increments('id');
$table->unsignedInteger('thread_id');

线程表:

$table->increments('id');
$table->string('title', 500);

关系报告 -> 话题

 public function thread() {
    return $this->hasOne(Thread::class, 'id');
 }

所以我这样做:

Report::with('thread')
        ->groupBy('thread_id')
        ->get();

但是,我收到此错误:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'reports.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from `reports` group by `thread_id`)

知道如何解决此问题或以其他方式解决此问题吗?谢谢!

【问题讨论】:

  • Group by clause in mySQL and postgreSQL, why the error in postgreSQL? sql_mode=only_full_group_by 需要用 agg 函数包装每一列。
  • 如果不了解您的意图,就很难说。在不选择聚合(总和、计数等)的情况下按某些内容进行分组是没有任何意义的。你能详细解释一下你正在尝试做什么/实现什么吗?

标签: mysql laravel eloquent query-builder laravel-query-builder


【解决方案1】:

我会这样做:

第一: 在线程模型中创建这样的关系:

public function reports() {
    return $this->hasMany(Report::class);
}

秒:

  • 在控制器中将获取至少具有报告计数的报告的所有线程,如下所示:

$threads = Thread::has('reports')->withCount('reports')->get()

  • 在视图中你可以像这样打印出来

@foreach($threads 作为 $thread)
{{ $thread->id 。 ' 已 ' 。 $thread->reports_count 。 '报告'}}
@endforeach

【讨论】:

  • 就是这样。非常感谢,很棒的解决方案。
  • 还有一个问题。我想按报告日期对结果进行排序,以便首先显示已报告的线程。这种方式可行吗?
  • @Hillcow 在threads 表中添加新列并将其命名为类似last_report_at 并在创建新报告时对其进行更新,然后使用该列对其进行排序
【解决方案2】:

也许这行得通:

Report::with('thread')
    ->get()
    ->groupBy('thread_id');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 2018-06-12
    • 2017-07-29
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2020-03-17
    相关资源
    最近更新 更多