musqsim's avatar

Retrieve data with HAS Relationship

Hello, guys,

I'm trying to get all Patients that had Sessions in a specific year. All models are defined and have their relationship.

$patients = Patient::where('status', 1)->has('sessions')->whereYear('start_date', $date['year'])->get();

My point here is: "start_date" in this query is regarding to Patient, but I need to make it to "Sessions".

How to do it without DB Raw?

Many thanks

0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
Patient::where('status', 1)
  ->whereHas('sessions', fn($q) => $q->whereYear('start_date', $date['year']))
  ->get();
musqsim's avatar

@Sergiu17 thank you, thats what I get to work also:

$patients = Patient::where('status', 1)->whereHas('sessions', function($query) use($date) { $query->whereYear('start_date', $date['year']); })->get();

Please or to participate in this conversation.