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' => '标题', 'cid' => '分类', 'content' => '内容', ]; } /** * 指定校验场景 * @return array */ public function scenarios() { $parentScenarios = parent::scenarios(); $customScenarios = [ 'add' => ['title', 'cid', 'content'], 'edit' => ['id','title', 'cid', 'content'], ]; 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]); } else { $this->addError('edit', '提交场景不存在'); return null; } $model->TITLE = $this->title; $model->CID = $this->cid; $model->CONTENT = ''; $model->STATUS = 1; 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; } }