简体   繁体   English

使用预先加载过滤结果

[英]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: 我有以下表格:

  1. foods 食品
  2. shops 商店
  3. shop_food shop_food
  4. users 用户
  5. comments 评论

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 . 如果记忆whereHaswhereHas实际上不会为你填充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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM