tp5 关键字模糊查询 日期查询 小于大于某范围等查询的优点

挺不错,用熟了这tp5封装的很方便.

类似上边一个查询多个操作,基本在model 一个方法搞定代码也不用很多,

首先要学会用scope  网上搜tp scope 有几个例子可以借鉴

model 内添加

 protected $searchField = [
        'devid',
        'devphone',
        'bindphone'
    ];
    protected $whereField = [
        'endtime',
        'isactived',
        'issold',
        '_date_range_'
    ];

上两个 是为了下边的方法  网页提交的参数传递到这个方法内滤掉 value 为空的,不为空的值进行查询, 如果条件都不为空,相当于where  xxx条件  and xxx条件 这个还需进一步测试,并不确定具体

  public function scopeTestWhere($query, $where)
    {
        if (count($this->whereField) > 0 && count($where) > 0) {
            foreach ($where as $key => $value) {
                if (in_array($key, $this->whereField) && $value!="") {
                    if($key=='endtime')
                    {
                     //   where('score','<',80);
                        $query->where($key,'<', $value);
                      continue;
                    }
                  if($key=='_date_range_')
                    {
                       $datefrom=mb_substr($value,0,10);
                        $dateend=mb_substr($value,13,10);
                        $query->where('activedate','between time', [$datefrom,$dateend]);
                        continue;
                    }
                    $query->where($key, $value);
                }
            }
        }
    }

控制器内 把网页传过来的值 交给 testwhere 处理

$param = $request->param();
  $data  = $model->scope('search', $param['_keywords'] ?? false)       
         ->scope('testwhere', $param)
           ->order($param['_order'] ?? 'id', $param['_by'] ?? 'desc')
         ->paginate($this->admin['per_page'], false, ['query'=>$request->get()]);

猜你喜欢

转载自www.cnblogs.com/zuochanzi/p/11355447.html