//查询条件为二维数组 [[key,field,value],[key,value]]
/**
* 查询数据列表
* @param array $where //查询条件 二维数组[key,field,value] field省略的情况下默认为 =
* @param string $field //筛选字段
* @param array $with//关联模型
* @param int $page //页码
* @param int $limit// 条数
* @return array [total,list]
*/
public function getLists(array $where, string $field = '*', array $with = [], int $page, int $limit)
{
$queryBuilder = $this->buildWhereConditions($where);
$list = $queryBuilder->field($field)->with($with)->page($page, $limit)->select()->toArray();
$total = $queryBuilder->count();
return compact('total', 'list');
}
public function buildWhereConditions($conditions)
{
return $this->getModel()->where(function ($query) use ($conditions) {
foreach ($conditions as $condition) {
if (count($condition) == 3) {
[$field, $operator, $value] = $condition;
} else {
$operator = '';
[$field, $value] = $condition;
}
switch ($operator) {
case 'like':
$query->where($field, 'like', $value);
break;
case 'between':
$query->whereBetween($field, $value);
break;
case 'in':
$query->whereIn($field, $value);
break;
// 可以根据需要添加其他操作符的处理
case '=':
$query->where($field, '=', $value);
break;
default:
$query->where($field, '=', $value);
break;
}
}
});
}
Last modification:January 12, 2024
© Allow specification reprint