Laravel query builder group by error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

Laravel query builder group by error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

我正在建立一个论坛。我有两个模型:Thread 和 Report。

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

我正在制作一个页面以显示已报告给版主的话题。

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

报告table:

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

线程 table:

$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`)

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

也许这行得通:

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

我会这样做:

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

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

秒:

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

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

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

@foreach($threads as $thread)
{{ $thread->id . ' has ' . $thread->reports_count . ' report'}}
@endforeach