无论什么情况,整数都被标记为脏属性

时间:2019-07-01 17:39:43

标签: yii2

我需要检查模型是否已更新以及保存时更改了哪些属性。

我正在使用dirtyAttributes,并按照docs的建议过滤intval。 这些值来自API,并且在输入时会进行类型转换,因此从理论上讲,过滤器是多余的。

模型规则

public function rules()
{
    return [
        [['contract_date', 'order_date'], 'integer'],
        [['contract_date', 'order_date'], 'filter', 'filter' => 'intval'],
    ];
}

这是当前正在运行的一些代码:

// Add the changed status variables to the job log
$dirty_attributes = array_keys($model->dirtyAttributes);
if($model->save()) foreach ($dirty_attributes as $attribute)
{
    $data[$attribute] = $model->getOldAttribute($attribute).' ('.gettype($model->getOldAttribute($attribute)).')'. ' => '. $model->$attribute.' ('.gettype($model->$attribute).')';
}
var_dump($data);

这将产生:

["contract_date"]=>
string(44) "1559669638 (integer) => 1559669638 (integer)"
["order_date"]=>
string(44) "1559669638 (integer) => 1559669638 (integer)"

我可能缺少明显的东西,但我能理解。

1 个答案:

答案 0 :(得分:0)

保存模型后,所有“ oldAttributes”都会更新以存储新值,因此像您那样进行比较是没有意义的。如果要在保存后检查哪些属性已更改,可以在模型中覆盖afterSave()方法,例如:

public function afterSave($insert, $changedAttributes)
{
    // $changedAttributes -> this is it
    parent::afterSave(); // call parent to trigger event
}

或监听还会传递此数据的ActiveRecord::EVENT_AFTER_INSERT / ActiveRecord::EVENT_AFTER_UPDATE事件。