Laravel 预加载 4 个表

Laravel eager loading 4 tables

我在 laravel 中遇到 'eager loading' 的问题。

我正在处理 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';
}

?>

现在我想'get'一个对象中的所有数据。

当我这样做时:

$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)

这样做:

AgendaPersonalModel::with(['periods', 'periods.weekdays' => function ($q) {
        $q->with('breaks');
    }])->find(1);

你可以做到这一点

$agendaTest = AgendaPersonalModel::with(['periods', 'periods.weekdays.breaks'])->where('id', 1)->first();