加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Yii on update,检测是??否在beforeSave()上更改了特定的A

发布时间:2020-12-13 22:41:14 所属栏目:PHP教程 来源:网络整理
导读:我在模型的beforeSave上引发了一个Yii事件,只有在模型的特定属性发生变化时才会触发该事件. 我现在能想到如何做到这一点的唯一方法是创建一个新的AR对象并使用当前的PK查询旧模型的数据库,但这不是很好地优化. 这就是我现在所拥有的(注意我的表没有PK,这就是
我在模型的beforeSave上引发了一个Yii事件,只有在模型的特定属性发生变化时才会触发该事件.

我现在能想到如何做到这一点的唯一方法是创建一个新的AR对象并使用当前的PK查询旧模型的数据库,但这不是很好地优化.

这就是我现在所拥有的(注意我的表没有PK,这就是我查询所有属性的原因,除了我要比较的那个 – 因此未设置的函数):

public function beforeSave()
{
    if(!$this->isNewRecord){ // only when a record is modified
        $newAttributes = $this->attributes;
        unset($newAttributes['level']);
        $oldModel = self::model()->findByAttributes($newAttributes);

        if($oldModel->level != $this->level)
            // Raising event here
    }
    return parent::beforeSave();
}

有更好的方法吗?也许将旧属性存储在afterFind()中的新本地属性中?

您需要将旧属性存储在AR类的本地属性中,以便您可以随时将当前属性与旧属性进行比较.

步骤1.向AR类添加新属性:

// Stores old attributes on afterFind() so we can compare
// against them before/after save
protected $oldAttributes;

步骤2.覆盖Yii的afterFind()并在检索原始属性后立即存储它们.

public function afterFind(){
    $this->oldAttributes = $this->attributes;
    return parent::afterFind();
}

步骤3.比较beforeSave / afterSave中的旧属性和新属性或AR类中您喜欢的任何其他属性.在下面的示例中,我们将检查名为“level”的属性是否已更改.

public function beforeSave()
{
    if(isset($this->oldAttributes['level']) && $this->level != $this->oldAttributes['level']){

            // The attribute is changed. Do something here...

    }

    return parent::beforeSave();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读