【问题标题】:Laravel - constrain on eager loaded belongsTo relationshipLaravel - 约束急切加载的 belongsTo 关系
【发布时间】:2013-12-25 03:17:51
【问题描述】:

我的模特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

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

【问题讨论】:

    标签: php orm laravel laravel-4 eloquent


    【解决方案1】:
    Book::whereHas('author' , function($query){
       $query->where('is_published', '=', '1');  
    })->get();
    

    使用它对我有用。

    【讨论】:

      【解决方案2】:

      问题是急切加载不使用 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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 这不起作用,因为 author_id 永远不会为空。我们总是有一个 author_id。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        • 2022-01-10
        相关资源
        最近更新 更多