无论如何,整数被标记为脏属性



我需要检查是否已更新模型,并且保存时哪些属性已更改。

正如文档所建议的那样,我正在使用DirtyAttributes和Filter 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)"

可能很明显我缺少了什么,但是我可以理解什么。

保存模型后,所有" 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事件。

最新更新