WhereHas() / orWhereHas not constraining the query as expected
I was using the method incorrectly. I loaded both associations first and then chained the whereHas
and orWhereHas
$broadcast->with('homeClub');
$broadcast->with('awayClub');
$broadcast->whereHas('homeClub', function($query) use ($parameterValues) {
$query->where('abb', 'liverpool');
})->orWhereHas('awayClub', function($query) use ($parameterValues) {
$query->where('abb', 'liverpool');
});
HowApped
Updated on July 16, 2022Comments
-
HowApped almost 2 years
I am using the new
whereHas
method to add a constraint on an eager loaded relationship in Laravel 4.1.$broadcast = $broadcast->whereHas('season', function ($query) use ($parameterValues) { $query->where('name', '2011-12'); });
In this example, I'm searching for a football/soccer broadcast where the relationship is that a
Broadcast
belongsTo
aSeason
I want to add a constraint for team (club) where the relationship is that a
Broadcast
hasOne
homeClub
and aBroadcast
hasOne
awayClub
. I want results for where a team (liverpool) is either the home or the away club so I try to use theorWhereHas
- a featured added in L4.1$broadcast = $broadcast ->with('homeClub') ->whereHas('homeClub', function($query) use ($parameterValues) { $query->where('abb', $parameterValues['club_abbs']); }); $broadcast = $broadcast ->with('awayClub') ->orWhereHas('awayClub', function($query) use ($parameterValues) { $query->where('abb', $parameterValues['club_abbs'] ); });
But this just seems to cancel out the constraint on the season that's mentioned in my first example. It's like, by chaining the the
orWhereHas
, mywhere
methods have 'forgotten' what they were constraining.