挺不錯,用熟了這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()]);