skip to Main Content

I have a query to return: All schedules that doesn’t have program or all schedules that have at least a program but the program is yet to end.

The issue is that, the query returns all schedules that doesn’t have a program and also all schedules that have a program where the program has ended.

Below is my code:

Schedule::where(['owner_id' => auth()->user()->owner->id,
            'session_id' => CurrentSession::fetchCurrentSession()->session_id
        ]) 
        ->whereDoesntHave('program', function(Builder $query){
            $query->where('end_date', null);
        })
        ->orderBy('schedule_time', 'asc')
        ->get();`

2

Answers


  1. Why no just simply use whereHas('program') instead?

    Login or Signup to reply.
  2. If you’re looking for a Schedule with no program relationship or a Schedule with a program that has a null end_date then you should specify that or in your query.

    Schedule::where([
            'owner_id' => auth()->user()->owner->id,
            'session_id' => CurrentSession::fetchCurrentSession()->session_id
        ])
        ->where(function (Builder $query) {
            $query->whereDoesntHave('program')
                ->orWhereHas('program', fn (Builder $q) => $q->whereNull('end_date'));
        })
        ->orderBy('schedule_time', 'asc')
        ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search