Laravel : 如何使用模型外的数据创建 groupBy 运行 并使用 where 子句

Laravel : how to create groupBy with data outside the model run and using where claus

我有以下这些模型: 赛季 :

public function club()
    {
        return $this->hasMany('App\Models\Club');
    }

俱乐部:

public function season()
    {
        return $this->belongsTo('App\Models\Season' ,'season_id');
    }
public function league()
    {
        return $this->belongsTo('App\Models\League' ,'league_id');
    }

联赛:

public function club()
    {
        return $this->hasMany('App\Models\Club');
    }

季节有名为状态的列,其值为 'active' 或为空。

俱乐部有赛季 ID 列。

现在我想 return 按联赛 ID 分组的俱乐部列表以及那些赛季状态为活动的俱乐部。 我创建了这个控制器,其中 return 个活跃赛季的俱乐部列表:

public function clubs_by_active_season()
    {
        $season = Season::where('status','active')->first();
        $season_id = $season->id;
        $clubs=Club::where('season_id',$season_id)->get();

        return $clubs;
    }

现在我想让它们按联赛 ID 分组,我该怎么做?

首先,根据关系类型重命名您的关系以帮助您形象化,因为它具有一对多关系,请使用复数名称

public function clubs()
{
    return $this->hasMany(Club::class);
}

使用clubs()函数建立查询关系并得到结果

public function clubs_by_active_season()
{
    $season = Season::where('status','active')->first();
    $clubs = $season->clubs()
        ->get() // Get the results
        ->groupBy("league_id"); // Group the collection by `league_id` key

    return $clubs;
}

我不确定这是否是您所说的“按 league_id 分组”的意思