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

问题描述 投票:4回答:1

我正在尝试搜索所有具有RentItem的租金,其书名为LIKE给定的$ input。

问题是当输入不匹配时,我仍然得到一个集合返回。唯一的区别是书籍关系是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();

租金模式关系

public function rentItems()
{
  return $this->hasMany(RentItem::class);
}

RentItems模型关系

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

public function rent()
{
     return $this->belongsTo(Rent::class);
}

我做过的研究:

php laravel collections nested-queries
1个回答
3
投票

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

$rents = Rent::whereHas('rentItems.book', function ($query) use ($input) { 
    $query->where('books.title', 'LIKE', "%$input%"); 
})->get();
© www.soinside.com 2019 - 2024. All rights reserved.