aftersave() 和 beforesave() 具有脏属性



我是新 Yii2。我陷入了在更新中触发更改属性的点。我只需要获取更改的属性并保存另一个表记录更改为新值。

请问任何人都可以帮助我解决这个问题,保存前,保存后和脏属性?

在 yii\db\ActiveRecord 中使用 getAttributes(( 和 getOldAttributes 方法。 即:

public actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$changed_attributes = array_diff_assoc($model->getOldAttributes(), $model->getAttributes());
if($model->save()) {
//Save changed values in other table
//$changed_attributes contains attribute_name=>value pairs of changed(old) attributes. and $model contains new values. 
}
}
}

在 ActiveRecord 模型中:

public function afterSave($insert, $changeAttributes)
{
parent::afterSave($insert, $changeAttributes);
// $changeAttributes
}

最新更新