laravel查询生成器group by error:select list的表达式#1不在group by子句中,并且包含未聚合的列

dnph8jn4  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(457)

我在建一个论坛。我有两个模型:线程和报表。
不同的用户可以多次报告一个线程。
我在一个页面上显示已报告给版主的线程。
现在的问题是,我将按线程对报告进行分组,这样就可以显示单个线程被报告了多少次,而如果同一个线程被报告了多次,它就不会出现多次。
报告表:

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

线程表:

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

关系报告->线程

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

所以我这样做:

  1. Report::with('thread')
  2. ->groupBy('thread_id')
  3. ->get();

但是,我得到一个错误:

  1. 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`)

你知道怎么解决这个问题或者用另一种方法吗?谢谢!

mbyulnm0

mbyulnm01#

我会这样做:
首先:在线程模型中创建如下关系:

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

第二:
在中,控制器将获取至少具有一个报告且报告计数的所有线程,如下所示:
$threads=thread::has('reports')->withcount('reports')->get()
在视图中你可以这样打印出来
@foreach($threads作为$thread)
{{$thread->id.'有'$线程->报告计数报告'}}
@endforeach公司

juud5qan

juud5qan2#

也许这样行得通:

  1. Report::with('thread')
  2. ->get()
  3. ->groupBy('thread_id');

相关问题