使用预先加载过滤结果

时间:2017-04-09 04:48:12

标签: php laravel-5

我正在laravel中为API创建搜索,但我的搜索给了我错误的结果。我想按地点和食物类型搜索。我有以下表格:

  1. 食品
  2. 商店
  3. shop_food
  4. 用户
  5. 评论
  6. 这是我的搜索代码:

     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;
    }
    

    我的结果是下面而不是仅仅记录了位置和食物,它显示了按位置过滤的所有商店,即使食物不匹配:enter image description here

1 个答案:

答案 0 :(得分:0)

您使用的with方法不会按您认为的方式进行过滤。您的代码实际上过滤了食物结果,告诉Eloquent检索所有Shop并且没有食物或名称为fish pepper的食物。这称为约束急切负载。

您要查找的方法是whereHas而不是with。这被称为查询关系存在。

$shops = Shop::where('city', '=', $location)
    ->with('comments.user')
    ->whereHas('foods', function($query) use($food){
        $query->where('name','=', 'fish pepper'); 
    })
    ->get();

现在只返回Shop个具有相应食品条目fish pepper的商品。

如果内存服务,whereHas实际上不会为您填充foods,但在这种情况下您不需要它,因为可以安全地假设它们都有fish pepper 。如果您确实想要提取所有食物,请将with('comments.user')更改为with(['comments.user', 'foods'])

可以找到whereHas的文档及其他实现方法[{3}}。

可以找到有关使用with方法执行操作的文档here

希望有所帮助。

相关问题