$patient = Patient::with('reports.analyzes')->find(1);
Laravel Eloquent - Retrieve data from pivot table
I'm trying to retrieve data from pivot table with where condition.
I have three tables:
- reports: id, patient_id, outcome
- analyzes: id, name, referenceValue
- analyzes_reports(pivot table): analyzes_id, reports_id
My Report.php model:
class Report extends Model { protected $table = 'reports'; protected $fillable = ['patient_id', 'outcome'];
public function patients()
{
return $this->belongsToMany('App\Patient');
}
public function analyzes()
{
return $this->belongsToMany('App\Analysis','analyzes_reports', 'analyzes_id', 'reports_id');
}
}
My Analysis.php model:
class Analysis extends Model { protected $table = 'analyzes'; protected $fillable = ['name', 'referenceValue']; public function reports() { return $this->belongsToMany('App\Report','analyzes_reports', 'analyzes_id', 'reports_id'); } }
My Patient.php model:
class Patient extends Model { // protected $table = 'patients'; protected $fillable = ['name', 'surname','tel'];
public function reports()
{
return $this->hasMany('App\Report');
}
}
Now, I want to retrieve data for example like this:
reports.id | patient.name | analyzes.name 1 John leukocytes 1 John erythrocyte 2 John erythrocyte 2 John glucose
So, one report with a certain patient may have multiple kinds of analyzes, because a patient can make more than one kind of analyzes.
The question is, how to retrieve data for example for John:
Report(1) patient(John) analyzes(leukocytes,erythrocyte) Report(2) patient(John) analyzes(erythrocyte,glucose)
Please or to participate in this conversation.