【问题标题】:filtering result using eager loading使用急切加载过滤结果
【发布时间】:2017-04-09 18:08:58
【问题描述】:

我正在 laravel 中创建一个 API 搜索,但我的搜索给了我错误的结果。我正在尝试按位置和食物类型进行搜索。我有以下表格:

  1. 食物
  2. 商店
  3. shop_food
  4. 用户
  5. cmets

这是我的搜索代码:

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

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

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    您使用的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();
    

    这现在将只返回 Shops 具有名称为 fish pepper 的相应食物条目。

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

    whereHas 的文档和实现此目的的其他方法可以在 here 找到。

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

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多