skip to Main Content

I have 2 models

  1. Patient model with id, name, address
  2. Appointment model with id, patient_id, appointment_date, status

Patient model has many Appointments.

I want to list Patients where patient’s previous Appointment status='closed' only. Beacause I dont want to add new appointment to a patient whose appointment status is open

How can I achieve this with eloquent ?

2

Answers


  1. you can query the patients with the desired condition using Eloquent:

    use AppModelsPatient;
    
    $patients = Patient::whereHas('appointments', function ($query) {
        $query->where('status', 'closed');
    })->get();
    

    Hope this helps!

    Login or Signup to reply.
  2. Use whereNotIn for excluding only the id’s that have status open and return all the patients:

    $Patients = Patient::whereNotIn('id', function($query){
            return $query->select('patient_id')->distinct('patient_id')->from('appointments')->where('status', '=', 'open');
        })->get();
    

    This eloquent query is same as in sql :

    select * from `patients` where `id` not in (select distinct `patient_id` from `appointments` where `status` = 'open')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search