查询字符串过滤具有来自同一列的不同值

时间:2017-06-01 22:14:07

标签: php laravel-5.4

我们如何按列中的多个值进行过滤? 示例:?name = comapny1& name = company2

例如,我有5家公司,我搜索的产品属于ti company1和company2,我想得到的结果是:包含属于company1和company2的产品的表

这是我的过滤器:

class ProductFilters extends QueryFilter
{
    // maker
    public function make($maker)
    {
        return $this->builder->where('company', $maker);
    }

查询过滤器:

<?php
/**
 * Created by PhpStorm.
 * User: dmitry
 * Date: 2017/05/10
 * Time: 2:26
 */

namespace App;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

abstract class QueryFilter
{
    protected $request;

    protected $builder;

    public function  __construct(Request $request)
    {
        $this->request = $request;
    }

    public  function apply(Builder $builder)
    {
        $this->builder = $builder;

        foreach ($this->filters() as $name => $value) {
            if (method_exists($this, $name)) {
                call_user_func_array([$this, $name], array_filter([$value]));
            }

        }

        return $this->builder;
    }

    public function filters()
    {
        return $this->request->all();
    }

}

我的表单如下:

<form method="GET" action="/products" id="form1">
  <input type="checkbox" name="company[]" value="1">1</input>
  <input type="checkbox" name="company[]" value="2">2</input>
</form>

这是我的控制者:

public function index(Request $request, ProductFilters $filters)
    {
        $products    = Product::filter($filters)->paginate(30)->appends($request->all());
        return view('product.browse', compact('products' ));
    }

1 个答案:

答案 0 :(得分:1)

说明使用whereIn

的基本示例
$companies = $request->company ?? [];
$products = Product::company($companies)->paginate(30);

class Product extends Model
{
    // ...

    public function company(Builder $query, ...$companies) 
    {
        return $query->whereIn('company', $companies);
    }

    // ...
}

使用带有OP代码的whereIn的示例。

class ProductFilters extends QueryFilter
{
    // ...

    public function make($maker)
    {
        return $this->builder->whereIn('company', (array) $maker);
    }

    // ...
}