Article::class, 'targetAttribute'=>'TITLE'], [['id'], 'exist', 'targetClass'=>Article::class, 'targetAttribute'=>'ID'], [['cid'], 'exist', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'ID'], ]; } public function attributeLabels() { return [ 'id' => 'ID', 'title' => 'Title',//标题 'cid' => 'Type', // 分类 'content' => 'Content', // 内容 'sort' => 'Sort', // 排序 ]; } /** * 指定校验场景 * @return array */ public function scenarios() { $parentScenarios = parent::scenarios(); $customScenarios = [ 'add' => ['title', 'cid', 'content', 'sort'], 'edit' => ['id','title', 'cid', 'content', 'sort'], 'sort' => ['id', 'sort'], ]; return array_merge($parentScenarios, $customScenarios); } /** * 申请 * @return Article|null * @throws \yii\db\Exception */ public function edit(){ if(!$this->validate()){ return null; } $db = \Yii::$app->db; $transaction = $db->beginTransaction(); try { if($this->scenario == 'add'){ $model = new Article(); $model->CREATED_AT = Date::nowTime(); } elseif($this->scenario == 'edit') { $model = Article::findOne(['ID'=>$this->id]); } elseif($this->scenario == 'sort') { $model = Article::findOne(['ID'=>$this->id]); } else { $this->addError('edit', 'Scenario not exists');// 提交场景不存在 return null; } $model->TITLE = $this->title; $model->CID = $this->cid; $model->CONTENT = ''; $model->STATUS = 1; $model->SORT = $this->sort; if(!$model->save()){ throw new Exception(Form::formatErrorsForApi($model->getErrors())); } // 暂时把内容写入到文件中 $path = \Yii::getAlias('@common/runtime/articleContent/').$model->ID; file_put_contents($path, $this->content); $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); $this->addError('edit', $e->getMessage()); return null; } return $model; } /** * 排序 * @return Article */ public function sortTo(): ?Article { if (!$this->validate()) { return null; } $model = Article::findOne(['ID' => $this->id]); $model->SORT = $this->sort; if (!$model->save()) { $this->addError('sortTo', Form::formatErrorsForApi($model->getErrors())); return null; } return $model; } }