Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mankowitz's avatar

Subquery includes deleted rows

OK, I know this is a bit complicated, but here goes.

A site has many patients, machines and meetings. Given a particular machine, I'd like to see the patients that are associated with it. When I give the following query, it includes patients who are soft-deleted. How can I enforce that only meetings with non-deleted patients are shown?

$site=Site::with('meetings', "meetings.patient", "meetings")->whereHas('machines', function($q) use($machine){ $q->where("machine_name", $machine); })->has("patients")->get()

yields

=> Illuminate\Database\Eloquent\Collection {#4113
     all: [
       App\Site {#4037
         id: 1,
         name: "Nursing Home 1 (basic)",
         meetings: Illuminate\Database\Eloquent\Collection {#4111
           all: [
             App\ZoomMeeting {#4084
               id: 1,
               patient_id: 29,
               site_id: 1,
               patient: App\Patient {#4094
                 id: 29,
                 first_name: "Ryan",
                 last_name: "Hill",
                 site_id: 43,
                 deleted_at: null,
               },
             },
             App\ZoomMeeting {#4104
               id: 2,
               provider_id: 2,
               patient_id: 1,
               site_id: 1,
               patient: null,
             },
           ],
         },
       },
     ],
   }

Note that in the second ZoomMeeting (#4104) patient is null.

Here are the relevant portions of my Models

class MachineName extends Model
{
    public function site()
    {
        return $this->belongsTo('App\Site');
    }
}
class Site extends Model
{
    use SoftDeletes;

    public function patients()
    {
        return $this->hasMany('App\Patient');
    }

    public function machines()
    {
        return $this->hasMany('App\MachineName');
    }

    public function meetings()
    {
        return $this->hasMany('App\ZoomMeeting');
    }
class ZoomMeeting extends Model
{
    use SoftDeletes;
    
    public function patient()
    {
        return $this->belongsTo('App\Patient');
    }
    
    public function site()
    {
        return $this->belongsTo('App\Site');
    }

}
0 likes
1 reply
Sinnbeck's avatar

ZoomMeeting does not seem to have a deleted_at column. Check your migration or database

But yes strange that the has does not work. Try using a callback to check deleted at

Please or to participate in this conversation.