前端样式:
前端代码:
<div class="layui-inline">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input name="search_account" placeholder="请输入" autocomplete="off" class="layui-input" type="text">
<input type="hidden" name="search_table_account" value="user">
</div>
</div>
<div class="layui-inline"><label class="layui-form-label">处理状态</label>
<div class="layui-input-block">
<select name="search_check_status" lay-verify="">
<option value="0">全部</option>
<option value="1" selected="selected">未处理</option>
<option value="2">已处理</option>
</select>
<input type="hidden" name="search_type_check_status" value="not_search">
<input type="hidden" name="search_table_check_status" value="personal_auth">
</div>
</div>
//提交表单后,结果
array(7) {
["search_account"] => string(3) "123"
["search_table_account"] => string(4) "user"
["search_check_status"] => string(1) "1"
}
代码解析:
两个例子。
注意表单的隐藏域,
value=“user”,表名
name=“search_table_account” ,search_table为固定写法,account,为user表中的字段
控制器代码
$requestData = $this->request->get();//获取表单提交数据
$where = createSearchWhere($requestData);//调用轮子
$count_imei = Db::name('personal_auth')
->alias('personal_auth')
->field('personal_auth.id , user.account, user.auth_source_platform_id')
->where($where)
->count();
重点
function createSearchWhere($data)
{
$where = [];
foreach ($data as $k => $v) {
if (substr($k, 0, 7) == 'search_' &&
substr($k, 0, 12) !== 'search_type_' &&
substr($k, 0, 13) !== 'search_table_'
) {
if ($v !== '' && $v !== null) {
$name = substr($k, 7);
//查看有没有表的指定
$table = '';
if (isset($data['search_table_' . $name])) {
$table = $data['search_table_' . $name];
$table .= '.';
}
//查看有没有搜索类型
if (isset($data['search_type_' . $name])) {
switch ($data['search_type_' . $name]) {
case 'time':
$v = explode(' - ', $v);
$where[$table . $name] = ['BETWEEN', $v];
break;
case 'not_search':
$where[$table . $name] = $v;
break;
}
} else {
$where[$table . $name] = ['like', '%' . $v . '%'];
}
}
}
}
return $where;
}
解析:就是把前端传来的数据拼接成一个where查询语句,还可以更换time类型(between),优点,无需每次写表单提交过来的where查询语句。
代码优化~