简体   繁体   English

Phalcon PHP:确定是否在模型验证方法中创建或更新

[英]Phalcon PHP: determine if create or update in model validation method

I've created a Model in Phalcon. 我已经在Phalcon中创建了一个模型。 In it, I have a validation() method. 在其中,我有一个validate()方法。 On create of a record, I want to make sure that a record is getting a name, but I don't want that to be required on update. 创建记录时,我要确保记录获得名称,但是我不希望更新时需要该名称。 How can I determine that with Phalcon? 我如何用Phalcon确定呢?

It is described better in the Phalcon's docs . 在Phalcon的文档中对其进行了更好的描述。



class Robots extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        //Skips fields/columns on both INSERT/UPDATE operations
        $this->skipAttributes(array('year', 'price'));

        //Skips only when inserting
        $this->skipAttributesOnCreate(array('created_at'));

        //Skips only when updating
        $this->skipAttributesOnUpdate(array('modified_in'));
    }

}

If you have something more complex and want to use the same 'validation' method for both creates and updates you can do this: 如果您有更复杂的东西,并且想要使用相同的“验证”方法进行创建和更新,则可以执行以下操作:

public function beforeValidationOnCreate()
{
    $this->_isCreate = 1;
}

public function beforeValidationOnUpdate()
{
    $this->_isCreate = 0;
}

public function validation()
{
    if ($this->_isCreate) {
        // ...
    } else {
        // ...
    }
}

You can do your validations within a function called beforeValidationOnCreate or beforeCreate and it gets hit only on Creation and not updating 您可以在一个名为beforeValidationOnCreate或beforeCreate的函数中进行验证,并且仅在创建时才会命中它,而不会更新

public function beforeValidationOnCreate()
{
    //Do the validations
}

or 要么

class MyModel extends \Phalcon\Mvc\Model
{
    public function beforeCreate()
    {
        //Do the validations
    }
}

Check the link below for more Events that you could use : 检查下面的链接以获取更多可以使用的事件:

Phalcon PHP Events and Events Manager Phalcon PHP事件和事件管理器

Hope that is close to what you need 希望接近您的需求

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

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