2017-07-19 150 views
2

我有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) 
+0

你對'AgendaPersonalModel'定義一個工作日的關係?或者你是否想要做'periods.weekdays.breaks'? – Josh

+0

他喬希,它歸結爲:'periods.weekdays.breaks' –

回答

2

你可以做到這一點

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

這是行不通的。嵌套預熱加載僅適用於1或2級關係。 –

+0

偉大的,我嘗試過這樣的事情,但我現在看到我的錯誤。對我而言,這是最好的解決方案,ALOT –

0

待辦事項這個:

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

工作! :),謝謝ALOT –