2017-04-09 81 views
1

我正在laravel中创建一个API的搜索,但是我的搜索给了我错误的结果。我正在尝试按地点和食物类型进行搜索。我有以下表格:使用预热过滤结果

  1. 食品
  2. 商店
  3. shop_food
  4. 用户
  5. 评论

这里是我的搜索代码:

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

回答

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 S作名为fish pepper相应的食品入境。

如果没记错,whereHas实际上不会填充foods你,但在这种情况下,你不需要它,因为它是安全的假设,他们都有fish pepper。如果您确实想要取出所有食物,请将with('comments.user')更改为with(['comments.user', 'foods'])

whereHas和其他方式的文件可以找到here

关于您在with方法中做什么的文档可以在here找到。

希望有所帮助。