假设我有一个模型:种族、参与者、团队
这些关系:种族 1-N
参与者 N-1
团队
换个角度看:
races 1 - N participants
teams 1 - N participants
用 Laravel 术语来说:
/* Inside Race model */
public function participants()
{
return $this->hasMany(Participant::class);
}
/* Inside Team model */
public function participants()
{
return $this->hasMany(Participant::class);
}
/* Inside Participant model */
public function race()
{
return $this->belongsTo(Race::class);
}
public function team()
{
return $this->belongsTo(Team::class);
}
在 participants
表,看起来像这样:
id | team_id | race_id | [a lot of other columns...]
------------------------------
1 | 1 | 1 |
2 | 1 | 1 |
3 | 2 | 1 |
4 | 2 | 1 |
在上面的例子中,我知道种族 ID 1
有2 teams
.
我可以count
他们这样做:
$race = Race::find(1);
$number = $race->participants()->distinct()->count('team_id');
问题
Counting
团队数量很酷,但我想访问相应的 Team
的列表模型实例,以便我可以将它们用于进一步的操作(例如在 foreach
循环内)。
我尝试了很多事情但没有成功。
像这样的事情:
$teams = $race->participants()->distinct()->[...] // Don't know what to put here
等效的 SQL 查询是:
SELECT teams.* FROM teams
INNER JOIN participants ON participants.team_id = teams.id
INNER JOIN races ON races.id = participants.race_id
WHERE races.id = 1
GROUP BY teams.id
结果是:
当 participants
表包含以下内容:
我想知道我是否可以使用Eloquent
来做到这一点而不是使用Query/Builder DB::
直接方法?
编辑1
我最接近的结果:
$race->participants()->distinct()->get('team_id')
然后使用 team_id
的列表我可以使用 Team::find([list of IDs])
访问团队但它对我来说看起来很贪婪。
编辑2
我忘记了一些信息:
participants.team_id
列是NULLABLE
因为:- 有
races
与teams
的participants
- 有
races
与participants
(没有team
)
- 有
最佳答案
我认为您无法通过 $race
实例轻松访问它。
但是,您可以在 Team
模型上使用 whereHas
方法:
$race = Race::find(1);
$teams = Team::whereHas('participants', function ($query) use ($race) {
$query->where('race_id', $race->id);
})->get(); // ->count() also works
关于php - 在 Laravel 中使用 Eloquent 检索关系的不同关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61891205/