We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Foreign key validation when related model does not exists

Hi, is possible exclude loading relations in model validation? I dont think this is good to create exception when you could not load related model. The best would be use message defined in definition of relation or create exception. In other case you dont have any chance skip this "feature" until you define beforeValidation function, go through all relations, check foreign keys and from those create new validation message. Using this on php layer validation will be definitely slower. I use following code in my abstract model class which extends \Phalcon\Mvc\Model.

public function beforeValidation()
{
        $relations = $this->getModelsManager()->getRelations(get_class($this));
        $valid = true;

        foreach ($relations as $relation) {
            $fields = $relation->getFields();
            $foreignKey = $relation->isForeignKey();

            if (!$foreignKey) {
                continue;
            }

            if (is_string($fields)) {
                $fields = array($fields);
            }

            foreach ($fields as $field) {
                if (in_array($field, array('skip specific fields', ...))) {
                    continue;
                }                

                if (empty($this->$field)) {
                    $options = $relation->getOptions();
                    $message = 'This field cannot be left blank.';
                    if (isset($options['message'])) {
                        $message = $options['message'];
                    }

                    $this->appendMessage(new Message($message, $field, 'PresenceOf'));
                    $valid = false;
                }
            }
        }

        return $valid;
}

If I've understood correctly, this is a known issue.

https://github.com/phalcon/cphalcon/issues/2039