简体   繁体   English

“独立”模式下的Phalcon \\ Mvc \\ Model \\ Validator \\ Uniqueness

[英]Phalcon\Mvc\Model\Validator\Uniqueness in “standalone” mode

I'd like to use Phalcon\\Mvc\\Model\\Validator when validating my Model before save. 保存前验证模型时,我想使用Phalcon \\ Mvc \\ Model \\ Validator。 The problem, however, is that I'd like to check for field's uniqueness in some OTHER model, and not the one I am currently validating. 但是,问题在于,我想检查某些其他模型中字段的唯一性,而不是我当前正在验证的那个模型。

For example, there's a form that allows you to send email invitations to new users. 例如,有一种表格可以让您向新用户发送电子邮件邀请。 I would like to ensure that my Invitation model fails validation if someone tries to reuse an email address of existing User model (you should not be allowed to invite an existing user). 如果某人尝试重用现有用户模型的电子邮件地址,我想确保我的邀请模型无法通过验证(不应允许您邀请现有用户)。

How can do this in my Invitation Model: 如何在我的邀请模型中做到这一点:

public function validation()
{
    $this->validate(new Uniqueness(array(
        'field' => 'email'
    )));
}

How can I tell Uniqueness that it should check 'email' field in User model, as opposed to Invitation model? 我怎样才能告诉Uniqueness,它应该检查用户模型中的“电子邮件”字段,而不是邀请模型?

Thanks! 谢谢!

One way I can think of achieving this would be to use custom validations, 我可以想到的一种方法是使用自定义验证,

Check following code for reference 检查以下代码以供参考

class UniqueValidatorUser extends Validator implements ValidatorInterface
{
    public function validate($record)
    {
        $field = $this->getOption('field');
        $value = $record->readAttribute($field);
        $users = Users::find(array(
                                "conditions" => array("name" => $value)
                            ));

        if(count($users) == 1)
        {
            $this->appendMessage("The Name is already in use", $field, "Unique");
            return false;
        }
        return true;
    }
}

Within your invitation model you will have to put following code, 在邀请模型中,您将必须输入以下代码,

public function validation()
        {

            $this->validate(new UniqueValidatorUser(array(
                                    "field"  => "email",
                                )));
         }

Refer http://docs.phalconphp.com/en/latest/reference/validation.html for more! 有关更多信息,请参考http://docs.phalconphp.com/en/latest/reference/validation.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM