Dmitry
Dmitry

Reputation: 581

Sequelize ORM relations vs foreign keys

I'm about to start new solo project and use Sequelize ORM which I've used in another projects with my colleagues. I've searched a little more SQ docs and figured out that SQ support both model relations and classic foreign keys. I am foreign keys fan but model relations also is powerful way to organize database models and potentialy has more flexibility then foreign keys (IMHO).

So can somebody give an advice of what is better to use in different cases or database architectures?

My new project must not have some polymorphic relations and other strange and difficult structures (at least I hope so) but it will be long-time product with multiple functions and abilities so it have to be flexible enough. Also I don't plan to use anything but project ORM to modify database (mariadb).

Upvotes: 0

Views: 213

Answers (1)

dmfay
dmfay

Reputation: 2477

Model relations do not offer more power or flexibility than foreign keys: they're the framework's way of expressing those same relationships. A.belongsTo(B), for example, is a "Sequelizey" way of saying that an A record has a foreign key to a B record, which is how the dependency is established in the database schema (if you do establish a hard dependency, which Sequelize allows you to skip).

When it comes to making relationships explicit, it's important to remember that database-level constraints are law, and the only way to really ensure that your data stays correct. Anything else -- including the definition of hasOne or belongsTo in your models -- is advice which may be respected sometimes and so cannot guarantee integrity. Use proper foreign key constraints.

Upvotes: 2

Related Questions