【问题标题】:Laravel belongsToMany withPivot() and distinct()Laravel belongsToMany withPivot() 和 distinct()
【发布时间】:2022-12-05 20:06:14
【问题描述】:

如何对具有 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');
    }

错误

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

【问题讨论】:

    标签: laravel distinct


    【解决方案1】:

    您可以使用 SELECT 子句来指定结果中应包含哪些列。这允许您指定哪些列应包含在结果中,同时仍按 chores.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');
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2015-04-26
      • 2015-01-16
      • 1970-01-01
      • 2015-02-22
      • 2018-08-10
      相关资源
      最近更新 更多