modelInstance === null) { $modelClass = $this->setModel(); $this->modelInstance = new $modelClass(); } return $this->modelInstance; } /** * 根据条件获取一条数据 * @param array $where * @param string|null $field * @param array $with * @return array|Model|null * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public function getOne(array $where, ?string $field = '*') { return $this->getModel()->where($where)->field($field)->findOrEmpty(); } /** * @param array $where * @param string $field */ public function selectWhere(array $where, string $field = '*') { return $this->getModel()->where($where)->field($field)->select(); } /** * 读取数据条数 * @param array $where * @return int */ public function count(array $where = []): int { return $this->getModel()->where($where)->count(); } /** * 更新数据 * @param int|string|array $id * @param array $data * @param string|null $key * @return mixed */ public function update($id, array $data, ?string $key = null) { if (is_array($id)) { $where = $id; } else { $where = [is_null($key) ? $this->getModel()->getPk() : $key => $id]; } $data['updated_at'] = date('Y-m-d H:i:s'); return $this->getModel()->where($where)->update($data); } /** * 插入数据 * @param array $data * @return mixed */ public function save(array $data) { $data['created_at'] = date('Y-m-d H:i:s'); return $this->getModel()->create($data); } /** * 插入数据 * @param array $data * @return mixed */ public function saveAll(array $data) { $data['created_at'] = date('Y-m-d H:i:s'); return $this->getModel()->insertAll($data); } /** * 求和 * @param array $where * @param string $field * @param bool $search * @return float */ public function sum(array $where, string $field) { return $this->getModel()->where($where)->sum($field); } /** * 某个字段累加某个数值 * @param string $field * @param int $num */ public function incField(array $where, string $field, $num = 1) { return $this->getModel()->where($where)->inc($field, $num)->update(); } /** * 某个字段累加某个数值 * @param string $field * @param int $num */ public function decField(array $where, string $field, $num = 1) { return $this->getModel()->where($where)->dec($field, $num)->update(); } }