带有 where 子句查询的 Eloquent 嵌套关系在 false 条件下返回集合

Row*_*den 6 php collections nested-queries laravel

我正在尝试搜索所有具有 RentItem 且书名类似于给定 $input 的 Rent。

问题是当输入不匹配时,我仍然返回一个集合。唯一的区别是 book 关系为 null 而不是集合。

应返回 false 的查询结果:https : //pastebin.com/pd7UqhCi

查询结果为真:https : //pastebin.com/shndvdMh

当 book 等于 null 时,我不希望返回 Rent 模型。

我的查询

$rents = Rent::with(['rentItems.book' => function ($query) use ($input) { 
       $query->where('books.title', 'LIKE', "%$input%"); 
}])->get();
Run Code Online (Sandbox Code Playgroud)

租模型关系

public function rentItems()
{
  return $this->hasMany(RentItem::class);
}
Run Code Online (Sandbox Code Playgroud)

RentItems 模型关系

public function book()
{
     return $this->belongsTo(Book::class);
}

public function rent()
{
     return $this->belongsTo(Rent::class);
}
Run Code Online (Sandbox Code Playgroud)

我做过的研究:

Ale*_*nin 11

您需要使用该whereHas()方法。做这样的事情:

$rents = Rent::whereHas('rentItems.book', function ($query) use ($input) { 
    $query->where('books.title', 'LIKE', "%$input%"); 
})->get();
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢!像魅力一样工作。 (2认同)