代码之家  ›  专栏  ›  技术社区  ›  Paritosh Mahale

如何从beforeSave()之前获取数据

  •  1
  • Paritosh Mahale  · 技术社区  · 7 年前

    在我的系统中,我需要一个工具,它应该总是在实际表得到更新之前将旧记录复制到另一个表中。

    以便管理员可以查看新数据和旧数据(以维护新旧值的记录)

    为此,我使用 beforeSave() 方法

    public function beforeSave($insert)
        {
            if (!parent::beforeSave($insert)) {
                return false;
            }
    
            echo "<pre>before save";print_R($this);die();
            return true;
        }
    

    在更新案例中,我注意到 $this 返回旧记录和新记录

    $此 包含:

     app\models\Visitor Object (
         [_attributes:yii\db\BaseActiveRecord:private] => Array
             (
                 [id] => 1
                 [first_name] => new first name
                 [last_name] => new last name
                 [phone] => 987654321
                 [created_at] => 0000-00-00 00:00:00
                 [updated_at] => 0000-00-00 00:00:00
             )
    
         [_oldAttributes:yii\db\BaseActiveRecord:private] => Array
             (
                 [id] => 1
                 [first_name] => old first name
                 [last_name] => old last name
                 [phone] => 123456789
                 [created_at] => 0000-00-00 00:00:00
                 [updated_at] => 0000-00-00 00:00:00
             )
    
         [_related:yii\db\BaseActiveRecord:private] => Array
             (
             )
    

    如果我使用 $this->first_name 它会返回新的值(新的名字)。 但是我如何访问旧数据(旧名字),以便在更新之前将其保存到另一个表中。

    或者任何其他实现这一目标的建议都是有益的。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Liauchuk Ivan    7 年前

    您可以使用方法 $this->getOldAttribute($name) ,其中name是要获取值的属性的名称。

    还有一种方法 $this->getOldAttributes() ,它返回具有旧属性值(名称-值对)的数组。