[TOC] #### 1. 構(gòu)建搜索器參數(shù) --- ``` /** * 模型搜索器參數(shù)構(gòu)造函數(shù) * * @param array $keys * @param array $where */ function where_filter(&$keys, array $where) { // 去掉數(shù)組里的空字符串和null $where = array_filter($where, function ($k) { return ($k === '' || $k === null) ? false : true; }); // 拿到所有鍵 $keys = array_keys($where); // 返回數(shù)組 return $where; } ``` #### 2. 根據(jù)時間范圍篩選 --- ``` /** * 追加獲取器 * * create_time_range 根據(jù)時間范圍篩選 */ public function searchCreateTimeRangeAttr($query, $value) { $query->whereBetweenTime('create_time', ...explode(' - ', $value)); } ``` #### 3. 根據(jù) nickname 字段模糊查詢 --- ``` /** * 根據(jù)nickname字段模糊查詢 * * @param [type] $query [description] * @param [type] $value [description] * @param [type] $data [description] */ public function searchNicknameAttr($query, $value, $data) { $value !== '' && $query->whereLike('nickname', '%' . $value . '%'); } ``` #### 4. hasWhere 根據(jù)關(guān)聯(lián)條件來查詢當(dāng)前模型對象數(shù)據(jù) --- **商家表** ```html mysql> select * from merch; +----+---------+-----------------+ | id | user_id | name | +----+---------+-----------------+ | 1 | 1 | 昊天宗 | | 2 | 2 | 七寶琉璃宗 | 2 rows in set (0.00 sec) ``` **用戶表** ```html mysql> select * from user; +----+--------+-------+ | id | name | score | +----+--------+-------+ | 1 | 張三 | 30 | | 2 | 李四 | 20 | | 3 | 王五 | 50 | +----+--------+-------+ 3 rows in set (0.02 sec) ``` **應(yīng)用場景: 在商家列表中根據(jù)用戶昵稱查詢商家** ``` public function searchNameAttr($query, $value, $data) { $query->hasWhere('user', function ($query) use ($value) { $query->whereLike('name', '%' . $value . '%'); }); } ```