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

Benefits of using model validators opposed to database constraints?

I have a question about model validators. I'm not sure I see what the benefit is of using the model validators.

For example Phalcon\Mvc\Model\Validator\Uniqueness. This helps ensure that the data is unique before inserting into the database, right?

But does this provide any extra benefit above and beyond just adding a constraint to the field in the database? The database is capable of handling this validation via a UNIQUE constraint. Why does Phalcon need to be aware of these constraints/validations and what extra benefit can it provide?



125.8k
Accepted
answer
edited Dec '14

In this case, validation woud prevent your database server from being hit. It may not be an issue for you, bu if you have tons of traffic, or your database is on a separate box than you web server, it could save you some headaches.

Other validations (ie: valid rhone number, email address, etc) can't be done via the database.

Thanks Quasipickle.

That actually makes a lot of sense. The only thing I could think of was maybe it provided better messages when errors occurred.

I have one follow up question. What do you feel the benefit is of defining relationships inside the database model. For example the hasMany(), hasOne(), or belongsTo() methods. This would suggest that Phalcon is able to determine validity of foreign keys. Can it do this without hitting the database to determine if that foreign key exists? Or is there a separate benefit to be had by defining these relationships?

Adding hasMany() relationships (for example), really lets you use the ORM to its full potential. I recommend checking the documentation on relationships - they have lots of relevant examples. I'm not 100% sure what validation Phalcon does with foreign keys - undoubtedly it would return errors if the database said the keys were invalid. The only way Phalcon wouldn't touch the database for stuff like this is if you've manually defined the schema for the model's respective table. It's a pain to do during development, but if DB performance is important, it does cut out quite a few queries.