[英]filtering result using eager loading
I am creating a search in laravel for an API but my search gives me the wrong results. 我在laravel中创建一个API搜索,但我的搜索给了我错误的结果。 I am trying to search by location and food type.
我想按地点和食物类型搜索。 I have the following tables:
我有以下表格:
Here is my search code: 这是我的搜索代码:
public function searchShop($food, $location)
{
//
if($food == " " || $location == " "){
return $this->index();
}
//get all records where city and food are equal to
$shops = Shop::where('city', '=', $location)
->with('comments.user')
->with(['foods'=> function($query) use($food){
$query->where('name','=', 'fish pepper'); }])
->get();
//check if empty and return all
if($shops->isEmpty()){
return $this->index();
}
return $shops;
}
my result is the below instead of just the record where location and food it shows all the shops filtered by location even where food isnt a match : 我的结果是下面而不是仅仅记录位置和食物显示所有商店按位置过滤即使食物不匹配:
The with
method that you're using does not filter in the way that you think it does. 您正在使用的
with
方法不会以您认为的方式进行过滤。 Your code actually filters the food results, telling Eloquent to retrieve all Shop
and either no foods, or the foods with the name fish pepper
. 您的代码实际上过滤了食物结果,告诉Eloquent检索所有
Shop
,或者没有食物,或者名称为fish pepper
的食物。 This is called constraining eager loads. 这称为约束急切负载。
The method you're looking for is whereHas
rather than with
. 您正在寻找的方法是
whereHas
而不是with
。 This is referred to as querying a relationships existence. 这被称为查询关系存在。
$shops = Shop::where('city', '=', $location)
->with('comments.user')
->whereHas('foods', function($query) use($food){
$query->where('name','=', 'fish pepper');
})
->get();
This will now return only Shop
s that have a corresponding food entry with the name fish pepper
. 这将只返回具有相应食物条目的
Shop
,名称为fish pepper
。
If memory serves, whereHas
won't actually populate foods
for you, but in this instance you wouldn't need it, as it's safe to assume that they all have fish pepper
. 如果记忆
whereHas
, whereHas
实际上不会为你填充foods
,但在这种情况下你不需要它,因为可以安全地假设它们都有fish pepper
。 If you do want to pull all foods, change with('comments.user')
to with(['comments.user', 'foods'])
. 如果您确实想要提取所有食物,请
with('comments.user')
更改with(['comments.user', 'foods'])
。
Documentation for whereHas
and other ways of achieving this can be found here . 有关
whereHas
和其他实现方法的文档可以在这里找到。
Documentation about what you were doing with the with
method can be found here . 可以在此处找到有关
with
方法执行操作的文档。
Hope that helps. 希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.