在Laravel / Eloquent中按倍数条件过滤模型

时间:2017-01-14 16:35:58

标签: php laravel eloquent

我想过滤产品列表。可以在route / q中访问API,我传递过滤参数,如/ 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查询。

3 个答案:

答案 0 :(得分: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'));
}

答案 1 :(得分:1)

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

答案 2 :(得分:1)

这是在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);