Laravel急切加载4个表

3

我在laravel中遇到了“急切加载”的问题。

我正在处理相互关联的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();

I get the following error:

(1/1) RelationNotFoundException
Call to undefined relationship [weekdays] on model [App\Models\AgendaPersonalModel].
in RelationNotFoundException.php (line 20)

你在AgendaPersonalModel中是否定义了工作日的关系?或者你是想使用 periods.weekdays.breaks 吗? - Josh
嗨,Josh,它归结为执行:“periods.weekdays.breaks”。 - user7447942
2个回答

2

你可以做到这一点

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

这样做不行。嵌套的急加载只适用于1或2个关系级别。 - Alexey Mezenin
太好了,我之前尝试过类似的东西,但现在我看到了我的错误。这是我情况下最好的解决方案,非常感谢。 - user7447942

0
做这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接