我如何 select 其关系模型属性在 Laravel 5.1 中等于 true 的行?

How do I select rows that their relationship models attribute is equals true in Laravel 5.1?

我有一个模型 Cart,其属性为 idclientIpcompleted。我有另一个名为 Item 的模型。 Item 模型与 Cart 模型有 belongsTo 关系。 Cart 模型与 Item 模型有 hasMany 关系。到目前为止一切顺利。

我如何获取所有 $items 他们的 $cart->completed 是真的?

如果我没有很好地解释我的问题,我真的很抱歉,我已经尽力了。

你可以试试这个..

$items = Item::whereHas('cart', function($q) { 
                 $q->where('completed', '=', 'true')
              })->get();
Item::whereHas('cart', function($query) {
    $query->where('completed', true);
})->get();

你只是在说:

Give me the items which have a cart that it's completed attribute is true.

official documentation 中有一个包含帖子和评论的示例。

$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

此查询将获取所有评论如 foo*.

的帖子