行为创建属性的验证规则

Validation rules on behavior-created attributes

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

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

生成的 created_by 属性具有可指责的行为:

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

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

有没有好的 yii2 方法来验证这样的行为生成的属性?

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

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