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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM