Laravel使用scope建立自定義where
阿新 • • 發佈:2018-12-26
/** * 多條件搜尋 * * @param $query * @param array $where 查詢條件 * @return mixed */ public function scopeMultiWhere($query, array $where) { return $this->buildWhere($query, $where); } /** * 構造查詢條件SQL語句 * * 查詢條件示例: * $where['field'] = $value; * $where['field'] = ['>=', $value1]; * $where['field'] = [['>=', $value1], ['<=', $value2]]; * * @param $query * @param mixed $where 查詢條件 * @return mixed */ public function buildWhere($query, $where) { if (!is_array($where)) { return $query; } foreach ($where as $field => $val) { if ($field && ($val || $val === 0)) { if (!is_array($val)) { $query->where($field, $val); } else { if (is_array($val[0])) { $query->where(function($query) use ($field, $val) { foreach ($val as $v) { if (!isset($v[1])) { $query->orWhere($field, '=', $v[0]); } else { $query->orWhere($field, $v[0], $v[1]); } } }); } else { switch ($val[0]) { case 'between': $query->whereBetween($field, $val[1]); break; case 'in': $query->whereIn($field, $val[1]); break; case 'notIn': $query->whereNotIn($field, $val[1]); break; case 'null': $query->whereNull($field); break; case 'raw': $query->whereRaw(str_replace('__field__',$field,$val[1])); break; default: $query->where($field, $val[0], $val[1]); } } } } } return $query; }
使用方法:
把上面的程式碼放到基Model裡,然後
- User::multiWhere($where)->get();
或者
- $query = DB::table('user');
- $this->buildWhere($query, $where);
- $query->get();
是不是方便多了,不用寫那麼多的->where()了