2013-12-07 72 views
1

我的模型BookLaravel - 限制對急於加載屬於關聯關係

public function author() 
{ 
    return $this->belongsTo('Author'); 
} 

我想這有有列is_published == 1

所以我已經嘗試了這個作者的所有書籍:

Book::with(['author' => function($query){ 

    $query->where('is_published', '=', '1'); 

}]); 

這個作品,但真的只是讓我的書,其中有些書有作者模型附加,有些不是!

所以,我嘗試這樣做:

Book::with(['author' => function($query){ 

    $query->where('is_published', '=', '1'); 

}])->has('author'); 

但我得到這個錯誤:

Has method invalid on "belongsTo" relations

我怎麼可以肯定,我在國外表約束減少了我的最終數據沒有必須循環訪問我的數據並檢查作者是否存在?謝謝。

回答

0

的問題是,預先加載不利用SQL JOIN(我知道的),如果你頭部到http://laravel.com/docs/eloquent#eager-loading你會看到的例子:

select * from books 

select * from authors where id in (1, 2, 3, 4, 5, ...) 

這並不讓筆者的約束現有。

要做到這一點,它需要一個JOIN如果你想有效地做到這一點(我認爲這樣,因此急切的加載)。

相關Laravel文檔:http://laravel.com/docs/queries#joins

0

更換has('author')whereNotNull('author_id')

+0

這不起作用,因爲author_id不會爲空。我們總是有一個author_id。 – phirschybar

1
Book::whereHas('author' , function($query){ 
    $query->where('is_published', '=', '1'); 
})->get(); 

使用它爲我工作。