Reputation: 2800
I am having a problem with simplyfing following eloquent relationship. It has a kind of nested query that uses a FieldRole model which I consider a bad pattern to follow. If I would have a raw query, then it should be evaluated as a one query using a join on field roles and it's name, but here it's doing two queries that probably are not cache'able by eloquent ORM.
class Team extends Model {
// ...
public function goalkeepers() {
return $this->belongsToMany(
SoccerPlayer::class,
'team_has_players',
'id_teams',
'id_soccer_players'
)->where(
'id_field_role',
FieldRole::where(
'name',
'Goalkeeper'
)
->first()
->getKey()
);
}
}
The second query is exectured there
FieldRole::where(
'name',
'Goalkeeper'
)
->first()
->getKey()
Is there a way to make it as a one query relationship?
Upvotes: 0
Views: 3795
Reputation: 25906
You can use a JOIN:
public function goalkeepers() {
return $this->belongsToMany(
SoccerPlayer::class,
'team_has_players',
'id_teams',
'id_soccer_players'
)->join('field_roles', function($join) {
$join->on('team_has_players.id_field_role', 'field_roles.id')
->where('field_roles.name', 'Goalkeeper');
});
}
Upvotes: 2