【问题标题】:aftersave() and beforesave() with dirty attributesaftersave() 和 beforesave() 带有脏属性
【发布时间】:2017-08-18 04:39:32
【问题描述】:

我是新的 Yii2。我陷入了在更新中触发更改属性的问题。我只需要获取更改的属性并将另一个表记录更改为新值即可。

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

【问题讨论】:

  • 请分享您的代码Minimal, Complete, and Verifiable example 或您迄今为止为解决问题所做或尝试过的任何事情
  • 我想更新产品详情。更新时,我需要将更改的值与以前的值一起保存在另一个具有类名和表 ID 的表中。我想我可以在保存和脏属性之前做到这一点。但我不清楚该怎么做。

标签: php yii2


【解决方案1】:

使用 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. 
        }
    }
}

【讨论】:

  • 您也可以使用:$model->getDirtyAttributes() 获取属性=>所有更改值的值对。
【解决方案2】:

在 ActiveRecord 模型中:

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

    // $changeAttributes
}

【讨论】:

  • 这个cahngeAttributes和dirtyAttributes一样吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多