/** * Finds the Merit model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Merit the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Merit::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * @param MeritTemplate $meritTemplate * @throws Exception */ public function update(MeritTemplate $meritTemplate) { $meritLog = new MeritLog(); $user = \Yii::$app->user->identity; $transaction = \Yii::$app->db->beginTransaction(); try { /** @var Merit $userMerit */ $userMerit = Merit::findOne(['user_id' => $user->getId(), 'type' => $meritTemplate->type]); // is sub 判断是否是减法 $actionSub = $meritTemplate->action_type == MeritTemplate::ACTIVE_TYPE_SUB; if ($userMerit) { $merit = call_user_func($actionSub ? 'bcsub' : 'bcadd', $userMerit->merit, $meritTemplate->increment); $userMerit->setAttributes(['merit' => (int) $merit]); } else { $userMerit = new Merit(); $userMerit->setAttributes(['merit' => ($actionSub ? '-' : '') . $meritTemplate->increment, 'user_id' => $user->getId(), 'username' => $user->username, 'type' => $meritTemplate->type]); } if (!$userMerit->save()) { Yii::error('Merit 操作失败' . json_encode(array_values($userMerit->getFirstErrors())), 'error'); throw new Exception(array_values($userMerit->getFirstErrors())[0]); } $description = $meritTemplate->title . ': ' . MeritTemplate::getActionTypes()[$meritTemplate->action_type] . $meritTemplate->increment . MeritTemplate::getTypes()[$meritTemplate->type]; $meritLog->setAttributes(['user_id' => $user->getId(), 'username' => $user->username, 'merit_template_id' => $meritTemplate->id, 'type' => $meritTemplate->type, 'description' => $description, 'action_type' => $meritTemplate->action_type, 'increment' => $meritTemplate->increment, 'created_at' => time()]); if (!$meritLog->save()) { throw new Exception(array_values($meritLog->getFirstErrors())[0]); } $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); } }