jk8Services = app(Jk8Services::class); $this->model = new UserMoneyLog(); } /** * 验证逻辑 */ protected function validateModelData(array $data, string $scene = ''): void { if (!$this->modelValidate) return; $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model)); if (class_exists($validateClass)) { $validate = new $validateClass(); if ($scene) $validate->scene($scene); $validate->check($data); } } /** * 查看 * @throws Throwable */ public function index(): void { if ($this->request->param('select')) { $this->select(); } list($where, $alias, $limit, $order) = $this->queryBuilder(); $res = $this->model ->withJoin($this->withJoinTable, $this->withJoinType) ->with($this->withTable) ->alias($alias) ->where($where) ->order($order) ->paginate($limit); $this->success('', [ 'list' => $res->items(), 'total' => $res->total(), 'remark' => get_route_remark(), ]); } /** * 添加 * @param int $userId * @throws Throwable */ public function add(int $userId = 0): void { if ($this->request->isPost()) { $data = $this->request->post(); if (!$data) { $this->error(__('Parameter %s can not be empty', [''])); } $result = false; $data = $this->excludeFields($data); $user = User::where('id', $data['user_id'])->find(); if ($data['type'] == 2) { $data['money'] = -$data['money']; } if ($user->money + $data['money'] < 0) { $this->error(__('Insufficient Credit')); } try { // 模型验证 $this->validateModelData($data, 'add'); $transactionId = $this->jk8Services->setScore($user['jk_username'], $data['money']); } catch (Throwable $e) { $this->error($e->getMessage()); } $this->model->startTrans(); try { $data['transaction_id'] = $transactionId; $data['created_by'] = $this->auth->getInfo()['id']; // $data['type'] = $data['money'] > 0 ? 1 : 2; $result = $this->model->save($data); $this->model->commit(); } catch (Throwable $e) { $this->model->rollback(); $this->error($e->getMessage()); } if ($result !== false) { $this->success(__('Added successfully')); } else { $this->error(__('No rows were added')); } } $user = User::where('id', $userId)->find(); if (!$user) { $this->error(__("The user can't find it")); } $this->success('', [ 'user' => $user ]); } /** * 编辑 * @throws Throwable */ public function edit(): void { $pk = $this->model->getPk(); $id = $this->request->param($pk); $row = $this->model->find($id); if (!$row) { $this->error(__('Record not found')); } $user = User::where('id', $row['user_id'])->find(); if ($this->request->isPost()) { parent::edit(); return; } $row['username'] = $user['username']; $row['nickname'] = $user['nickname']; $this->success('', [ 'row' => $row ]); } }