I have three tables which are related.
A site has many patients which have many complaints. Here are abbreviated models.
class Site extends Model
{
public function patients()
{
return $this->hasMany('App\Patient');
}
}
patient:
class Patient extends Model
{
public function site()
{
return $this->belongsTo('App\Site');
}
public function complaints()
{
return $this->hasMany('App\Complaint');
}
}
And finally, Complaint
class Complaint extends Model
{
public function patient()
{
return $this->belongsTo('App\Patient');
}
public function site()
{
return $this->patient->site;
}
}
So, my problem is that when I query complaints, I want to be able to get the site that the patient was in when that was generated.
Complaint::whereNull('resolved_at')->with('site')->get()
Gives me this:
Illuminate\Database\Eloquent\RelationNotFoundException with message 'Call to undefined relationship [site] on model [App\Complaint].'
One way to workaround was to add this to Complaint.php:
protected $appends = ['site'];
public function getSiteAttribute()
{
return $this->patient->site;
}
Which gives me this:
>>> Complaint::whereNull('resolved_at')->first()
=> App\Complaint {#211
id: 1,
reported_by: 7,
patient_id: 4,
problem: "Medicine made patient itchy",
provider_id: 2,
resolved_by: null,
// NOTE THAT site IS MISSING!!!
}
Surprisingly, however, this does work:
>>> Complaint::whereNull('resolved_by')->first()->site
=> App\Site {#217
id: 3,
name: "Nursing Home 3 (pro)",
site_info: null,
}
So, what is the best way to make sure that site is listed in the reply?