2016-09-22 145 views
9

該模型結構如下Laravel 5.3 withCount()嵌套關係

教程 - >(的hasMany)章節 - >(的hasMany)視頻

我們怎樣才能加載的從教程模型視頻(VIDEO_COUNT)數與laravel 5.3的withCount()方法

我曾嘗試:

Tutorial::withCount('chapters') 
->withCount('chapters.videos') // this gives error: Call to undefined method Illuminate\Database\Query\Builder::chapters.videos() 
->all(); 

編輯

這有效,任何更好的解決方案?

Tutorial::withCount('chapters') 
->with(['chapters' => function($query){ 
    $query->withCount('videos'); 
}]) 
->all(); 
+0

有你定義模型的關係? –

+0

你只需要做一個 - > withCount('chapters.videos')。另外,確保您的關係設置正確。 – 2016-09-22 15:22:24

+0

@DigitalFire關係是正確的,因爲我可以加載他們急切的加載。只是計數不會與withCount()方法填充 – crazy1337

回答

14

您只能在模型的定義關係上執行withCount()

然而,一個關係可以是hasManyThrough這將實現你在之後。

class Tutorial extends Model 
{ 
    function chapters() 
    { 
     return $this->hasMany('App\Chapter'); 
    } 

    function videos() 
    { 
     return $this->hasManyThrough('App\Video', 'App\Chapter'); 
    } 
} 

然後你就可以這樣做:

Tutorial::withCount(['chapters', 'videos'])

文檔:

+0

非常感謝你!我不認爲這樣更容易。 – july77

+0

感謝您的迴應。絕對幫助我提高了表現。 –