Laravel - 约束渴望加载的belongsTo关系

时间:2013-12-07 20:51:04

标签: php orm laravel laravel-4 eloquent

我的模型Book

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

如何确保我对外表的约束减少了我的最终数据集,而不必循环访问我的数据并检查作者是否存在?感谢。

3 个答案:

答案 0 :(得分:1)

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

使用它对我有用。

答案 1 :(得分: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

答案 2 :(得分:0)

has('author')替换为whereNotNull('author_id')

相关问题