我有两个数据库表
病人
--id
--name
报告
--id
--description
和枢轴塔
patient_report
--id
--report_id
--patient_id
我的患者模型
class Patient extends Model
{
public function reports()
{
return $this->belongsToMany('App\Report' , 'patient_reports');
}
}
我的报告模型
class Report extends Model
{
public function patients()
{
return $this->belongsToMany('App\Patient' , 'patient_reports');
}
}
我的ReportControlller
public function viewList($reportFloor = null)
{
$report = Report::orderBy('created_at' , 'desc')->paginate(50);
return view('admin.report_list' , ['reports' => $report]);
}
数据库:患者表有report_id列,报告表有patient_id列
N.B:我想找一个有报告的患者姓名。我正在使用像这样的laravel动态属性---
最后我的刀片
@foreach ($reports as $report)
{{ $report->patients->name }}
@endforeach
答案 0 :(得分:2)
试试这个:
@foreach ($reports->patients as $patient)
{{ $patient->name }}
@endforeach
答案 1 :(得分:0)
如错误所示,您正在尝试访问集合上的name属性。要修复你应该改变:
@foreach ($reports as $report)
{{ $report->patients->name }}
@endforeach
为:
@foreach ($reports as $report)
@foreach ($report->patients as $patient)
{{ $patient->name }}
@endforeach
@endforeach
答案 2 :(得分:0)
在你的控制器中,我会先找到患者,然后再获得他们的报告。
$patients = Patient::with('reports')->get();
然后在视图中我会这样做:
//This will first get all the patients
@foreach ($patients as $patient)
// This will get each of patients relational reports
@foreach ($patient->reports as $report)
{{ $report->name }}
@endforeach
@endforeach