【问题标题】:Filter models by multiples conditions in Laravel / Eloquent在 Laravel / Eloquent 中按多个条件过滤模型
【发布时间】:2018-08-08 12:01:00
【问题描述】:

我想过滤产品列表。该 API 可在路由 /q 中访问,我通过 /q?location=1,2&category=1,2,3 之类的过滤参数(如果未传递任何参数,它将获取所有位置/类别。

public function getProductsByQuery()
{
    $commaSeparatedLocations = Input::get('location');
    $commaSeparatedCategories = Input::get('category');


    if ($commaSeparatedLocations == null){
        $numberOfLocations = Location::count();
        for ($i=0;$i<=$numberOfLocations;$i++)
        {
            $locationsArray[$i] = $i;
        }
    } else {
        $locationsArray = $this->toArray($commaSeparatedLocations);
    }

    if ($commaSeparatedCategories == null){
        $numberOfCategories = Category::count();
        for ($i=0;$i<=$numberOfCategories;$i++)
        {
            $categoriesArray[$i] = $i;
        }
    } else {
        $categoriesArray = $this->toArray($commaSeparatedCategories);
    }

    return $products = Product::whereIn('category_id', $categoriesArray)->whereIn('location_id', $locationsArray)->paginate(config('app.products_per_page'));
}

public function toArray($commaSeparatedString)
{
    return explode(",",$commaSeparatedString);
}

而且,它有效。但我想知道如何改进我的代码。必须有一种更智能的方法,不需要那么多 SQL 查询。

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    这对我来说更具可读性:

    public function getProductsByQuery()
    {
        $q = Product::query();
    
        if (request('location')) {
            $q->whereIn('location_id', $this->toArray(request('location')));
        }
    
        if (request('category')) {
            $q->whereIn('category_id', $this->toArray(request('category')));
        }
    
        return $q->paginate(config('app.products_per_page'));
    }
    

    【讨论】:

    • 那是天才。非常感谢。
    • 太有趣了,我在哪里(或如何)可以找到有关此的更多信息?因为这个 query() 方法不在官方文档中。再次感谢。
    • @JorgeAnzola 您不会在文档中找到它,但您可以查看源代码以了解其工作原理。 query()Model 类中的一个方法,它只是创建一个新查询。
    【解决方案2】:

    如果你想要一个更复杂的查询/更多参数,你应该看看https://github.com/Tucker-Eric/EloquentFilter

    【讨论】:

      【解决方案3】:

      这是在 laravel 中过滤 sql 查询的最佳方法。

          $q = Product::query();
      
          $q->when(request('location'), function ($q) {
              return $q->where('location', request('location'));
          });
      
          $q->when(request('category'), function ($q) {
              return $q->where('category', request('category'));
          });
      
      
          $data['product_list'] = $q->paginate(5);
                       //OR
          $data['product_list'] = $q->get(5);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2018-12-05
        相关资源
        最近更新 更多