handleField($fields); $data = $this->buildWhere($where)->first($fields); if ($is_array) { return $data ? $data->toArray() : []; } return $data; } /** * 获取多条数据 * * @param array $where 查询条件 * @param string[] $fields 查询字段 * @param bool $is_array 是否返回数组格式 * @return Collection|array */ final public function get(array $where = [], array $fields = ['*'], bool $is_array = false) { $this->handleField($fields); $data = $this->buildWhere($where)->get($fields); $is_array && $data = $data->toArray(); return $data; } /** * 分页查询数据 * * @param array $where 查询条件 * @param array $fields 查询字段 * @param int $page 当前页 * @param int $size 每页条数 * @return array */ final public function paginate(array $where, $fields = ['*'], $page = 1, $size = 15): array { $this->handleField($fields); $model = $this->buildWhere($where); return $this->toPaginate($model, $fields, $page, $size); } /** * 根据条件更新数据 * * @param array $where 查询条件 * @param array $values 更新字段 * @return int */ final public function update(array $where, array $values): int { return $this->buildWhere($where)->update($values); } /** * 批量更新数据 * * @param array $where 查询条件 * @param array $values 更新字段 * @return int */ final public function batchUpdate(array $where, array $values): int { $data = []; foreach ($values as $field => $item) { if (!is_array($item)) { $data[$field] = $item; continue; } $when = ''; foreach ($item['filter'] as $k => $v) { $when .= sprintf(" when '%s' then '%s'", $k, $v); } $key = $item['field'] ?? $field; $string = "case $key {$when} else '{$item['default']}' end"; $data[$field] = Db::raw($string); } if (empty($data)) return 0; return $this->buildWhere($where)->update($data); } /** * 删除数据 * * @param array $where 删除的条件 * @return array */ final public function delete(array $where): array { return $this->buildWhere($where)->delete(); } /** * 打印查询 sql * * @param array $where 查询条件 * @return string */ final public function toSql(array $where): string { return $this->buildWhere($where)->toSql(); } /** * 原生 sql 查询 * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return array */ final public function sql(string $query, array $bindings = [], bool $useReadPdo = true): array { return Db::select($query, $bindings, $useReadPdo); } /** * 通过 model 读取分页信息 * * @param Builder $model 查询 Model * @param array $fields 查询字段 * @param int $page 当前分页 * @param int $size 分页大小 * @return array */ public function toPaginate(Builder $model, array $fields = ['*'], int $page = 1, int $size = 15): array { $total = $model->count(); $data = [ 'rows' => [], 'paginate' => [ 'page' => $page, 'size' => $size, 'total' => $total, ] ]; if ($total > 0) { $data['rows'] = $model->forPage($page, $size)->get($fields)->toArray(); } return $data; } }