if (!empty($this->req['seacherVal'])) {
$where[] = ['realname|username|phone', 'like', '%'.$this->req['seacherVal'].'%'];
}
来生成 where 子句,所以想了想写了一个方法来防止这种大量的重复判断现在使用
$data = [
"seacherVal" => "like,realname|username|phone",
"shopid" =>"idshop"
];
$where = buildWhere($data,$this->req);
就可以生成 where 子句,方法代码如下/**
* 根据传入得到 $data(格式详见参数介绍) 返回合适的 $where
* @param array $data 数据
* 示例 ["userid"=>"in,iduser","chanpinid"=>"idchanpin","in,test","test1"]
* 1.传入关联数组 键名是需要在 Request 中检索的字段。
* (1)如果键值使用 "," 隔开,逗号(英文)之前是 运算符 逗号(英文)之后是在数据库中被搜索的$request索引
* (2)如果键值没有使用 "," 隔开,默认使用 “=” 当作运算符,键值作为在数据库中被搜索的$request索引
* 2.传入 索引数组
* (1)如果键值使用 "," 隔开,逗号(英文)之前是 运算符 逗号(英文)之后的字符串 既是在 Request 中检索的字段 也是在数据库中被搜索的$request索引
* (2)如果键值没有使用 "," 隔开,默认使用 “=” 当作运算符,键值 既是在 Request 中检索的字段 也是在数据库中被搜索的$request索引
* @param Request $request
* @return array
*/
public function buildWhere($data,$request) {
$where = [];
//将 $data 键值对 依次放入闭包处理
array_walk($data,function ($value,$key) use($request,&$where) {
if(strstr($value,",")) {
//如果键值里有 逗号(英文)
$param = explode(",",$value);
}else {
//如果键值里没有 逗号(英文)
$param = ["=",$value];
}
if(is_numeric($key)) {
//如果传入的是索引数组,将值赋给键,键将用于在 $request 中检索
$key = $param[1];
}
if(!empty($request[$key])) {
//如果 $request 中存在 $key
if("like" == $param[0]) {
//如果运算符是 like 则要给 $request[$key] (将在被数据库中搜索的字段)加上通配符
$where[] = [$param[1],$param[0],"%".$request[$key]."%"];
}else {
$where[] = [$param[1],$param[0],$request[$key]];
}
}
});
return $where;
}
最佳答案
