Laravel:使用php数组搜索mysql LIKE

时间:2018-05-14 23:21:32

标签: php arrays

我有查询过滤器,用于过滤和搜索我的应用中的表格。

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

}

然后将过滤器添加到我想要使用它的模型中:

    public function scopeFilter($query, QueryFilter $filters)
    {
        return $filters->apply($query);
    }

然后为此模型创建一个ModelFilter:

class ModelFilters extends QueryFilter
{
    // search by one input
    public function name($name)
    {
        return $this->builder->where('name', $name);
    }

    // serch LIKE by one input
    public function name($name)
    {
        return $this->builder->where('name', 'LIKE', "%$name%");
    }

    // this function is not working
    public function name($name)
    {
        return $this->builder->whereIn('name', 'LIKE', "%(array)$name%");
    }
}

现在如何使用数组搜索数据库LIKE?

当前函数返回错误:

  

at HandleExceptions-> handleError(8,'Array to string conversion',   '/Users/apple/projects/laravel/app/ModelFilters.php',66,array('name'   => array('10','8'),'str'=>数组('10','8')))

1 个答案:

答案 0 :(得分:0)

最后!在朋友的帮助下,我们找到了解决方案。

    public function name($name)
    {
        for($i = 0; $i < count($name); $i++) {

            $this->builder->orWhere('name', 'LIKE', '%' . $chassis[$i] . '%');
        }

        return $this->builder;
    }