Laravel渴望加载4表
问题描述:
我有laravel'急切加载'的这个问题。Laravel渴望加载4表
我正与4个相互关联的表一起工作。
我有这些模态:
<?php
class AgendaPersonalModel extends Model
{
protected $table = 'agenda_personal';
public function periods() {
return $this->hasMany(AgendaPersonalPeriodModel::class, 'agenda_id');
}
}
?>
class AgendaPersonalPeriodModel extends Model
{
protected $table = 'agenda_personal_period';
public function weekdays() {
return $this->hasMany(AgendaPersonalWeekdaysModel::class, 'period_id');
}
<?php
class AgendaPersonalWeekdaysModel extends Model
{
protected $table = 'agenda_personal_weekdays';
public function breaks() {
return $this->hasMany(AgendaPersonalBreakModel::class, 'weekday_id');
}
}
?>
<?php
class AgendaPersonalBreakModel extends Model
{
protected $table = 'agenda_personal_breaks';
}
?>
现在我想将某个对象的 '得到' 的所有数据。
当我这样做:
$agendaTest = AgendaPersonalModel::with(array('periods', 'periods.weekdays'))->where('id', 1)->first();
它完美的作品
,但是当我这样做:
$agendaTest = AgendaPersonalModel::with(array('periods', 'periods.weekdays', 'weekdays.breaks'))->where('id', 1)->first();
我收到以下错误:
(1/1) RelationNotFoundException
Call to undefined relationship [weekdays] on model [App\Models\AgendaPersonalModel].
in RelationNotFoundException.php (line 20)
答
你可以做到这一点
$agendaTest = AgendaPersonalModel::with(['periods', 'periods.weekdays.breaks'])->where('id', 1)->first();
+0
这是行不通的。嵌套预热加载仅适用于1或2级关系。 –
+0
伟大的,我尝试过这样的事情,但我现在看到我的错误。对我而言,这是最好的解决方案,ALOT –
答
待办事项这个:
AgendaPersonalModel::with(['periods', 'periods.weekdays' => function ($q) {
$q->with('breaks');
}])->find(1);
+1
工作! :),谢谢ALOT –
你对'AgendaPersonalModel'定义一个工作日的关系?或者你是否想要做'periods.weekdays.breaks'? – Josh
他乔希,它归结为:'periods.weekdays.breaks' –