且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Octobercms验证关系用户

更新时间:2023-12-04 07:48:46

是的,I can Understand your problem.仅当您要添加新记录时才会发生这种情况.

Yes, I can Understand your problem. this will occur only when you are going to add new record.

它对于existing record来说将是完美的.因为existing record数据是persisted in database,所以我们可以表示一个工作记录,然后可以在其上触发relational validation.

It will work perfectly for existing record. as for existing record data is persisted in database so we can represent a working record and then we can fire relational validation on it.

但是对于new record,没有 ID ,这意味着记录it self没有保存在数据库中,因此与该关系字段没有任何关系,因此我们永远不会知道此字段是否附有某些值,并且验证将一直失败.

but for new record there is no ID means record it self is not saved in database so there will be no relation with that relational field so we never know this field has some value attached to it or not and validation will gonna fail all the time.

因此,无论您添加多少记录,都会在ERROR each time中显示请选择用户".

so no matter how much record you add, it will show ERROR each time that "please select user".

10月CMS使用differ binding,您可以看到可以添加用户而不保存当前记录.因为该数据存储在中间表中,所以在创建记录后relation data will be transferred to created record,因为现在它具有it's own ID and persisted in database.

October CMS use differ binding you can see you can add users without saving current record. as that data is stored in intermediate table so after record is created that relation data will be transferred to created record because now it has it's own ID and persisted in database.

因此对于解决方案,您需要使用differed binding scope在该模型内手动添加验证.

so for solution you need add validation manually inside that model, with differed binding scope.

首先rules

/**
 * @var array Validation rules
 */
public $rules = [
    'user' => 'required' <-- Remove this 
];

现在,我们将manual validation

将此code添加到您的model

public function beforeValidate() {

    // we need to check record is created or not
    if($this->id == NULL) {

        // CREATE CASE

        // we need to use differ binding scope as this record is not saved yet.
        if($this->user()->withDeferred(post('_session_key'))->count() == 0) {
            throw new \ValidationException(['user' => 'We need User !']);
        }
    }
    else {

        // UPDATE CASE

        // now record is created so we dont need differ binding
        if($this->user()->count() == 0) {
            throw new \ValidationException(['user' => 'We need User !']);
        }
    }
}

现在,验证可以用于both case,并且您可以为different cases添加其他验证.

Now Validation can work for both case and you can add different validation for different cases.

现在验证将正常工作.

如果您仍然发现问题,请发表评论.

if you still find issue please comment.