Laravel belongsToMany withPivot() and distinct()



如何对具有withPivot()值的belongsToMany()关系的结果进行分组?

groupBy()产生SQL错误,如果没有withPivot()数据,distinct()可以工作。

但是我需要结果中的枢轴数据。

// Relationship: room to chores
public function chores(){
return $this->belongsToMany(
Chore::class,
'maps'
)
->withPivot('id', 'room_id', 'chore_id', 'person_id')
->groupBy('chores.id');
}

SQL错误

SELECT list is not in GROUP BY clause and contains nonaggregated column 'pivot.maps.room_id' which is not functionally dependent on columns in GROUP BY clause

可以使用SELECT子句指定结果中应该包含哪些列。这允许您指定结果中应该包含哪些列,同时仍然按杂项对结果进行分组。id列。

public function chores()
{
return $this->belongsToMany(Chore::class, 'maps')
->select('chores.*', 'pivot.id', 'pivot.room_id', 'pivot.chore_id', 'pivot.person_id')
->withPivot('id', 'room_id', 'chore_id', 'person_id')
->groupBy('chores.id');
}

最新更新