行为创建的属性的验证规则

2024-01-19

我有一个具有两个值的模型,这两个值必须是唯一的。 Yii2对此有一个验证规则:

[['object_id', 'created_by'], 'unique', 'targetAttribute' => ['object_id', 'created_by']]

The created_by属性是通过可责备的行为生成的:

public function behaviors()
{
    return [
        'blameable' => [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'created_by',
            'updatedByAttribute' => 'updated_by',
        ],
    ];
}

验证是在行为输入存储到模型之前完成的。 (我知道这一点,因为如果created_by规则中要求,模型将不会保存 - 验证错误。)

有没有一个好的 yii2-way 来验证像这样的行为生成的属性?


您可以使用行为的“attributes”属性来指定将在其上创建属性的事件,因此您可以像这样修改模型:

public function behaviors()
{
    return [
        'blameable' => [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'created_by',
            'updatedByAttribute' => 'updated_by',
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_VALIDATE => ['updated_by', 'created_by']
            ]
        ],
    ];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

行为创建的属性的验证规则 的相关文章

随机推荐