vincent15000's avatar

How to add condition on a relationship if the relationship is present ?

Hello,

I need to add a condition on a relationship if the relationship is present. How is it possible to do that ?

Example

$events = Event::
    whereHas('teams', function ($query) use ($user) {
		// ...
	})
    ->get();

But this will filter the events which have teams. I need the events with and without teams, but for those which have teams, only retrieve the events if a certain condition is satisfied on the relationship between a team and a user (team_user table).

How is it possible to do that ?

Thanks for your help.

V

0 likes
7 replies
Sergiu17's avatar
Event::with(['teams' => function ($query) use ($user) {
		// ...
}])
1 like
vincent15000's avatar

@Sergiu17 @martinbean This will retrieve only the teams satisfying the condition.

What I need is to retrieve the events only if the user has joined the team before the date of the event.

The team_user table has a created_at field.

But for the events which have no team, I have to retrieve them all without any condition.

krisi_gjika's avatar
Level 14
$events = Event::query()
    ->whereHas('teams', function ($query) use ($user) {
		// ...
	})
    ->orWhereDoesntHave('teams')
    ->get();
1 like
krisi_gjika's avatar

@vincent15000 if you have other where conditions in the query, make sure to wrap these two in their own "where"

1 like
vincent15000's avatar

@krisi_gjika Humm ... I have to filter with a column in the pivot table. I have tried with $query->wherePivot but this works only inside the declaration of a relationship.

I start a new post for this specific question.

Please or to participate in this conversation.