Node.js › Databases & ORMs (MongoDB/Mongoose, SQL/Sequelize)
How does Sequelize define models and relationships for a relational (SQL) database in Node.js?
IntermediateAnswer
Sequelize defines models as JavaScript classes mapped to database tables, with each column's type and constraints declared explicitly, and relationships (one-to-many, many-to-many, one-to-one) declared via methods like hasMany(), belongsTo(), and belongsToMany() -- Sequelize then handles generating the underlying SQL joins and foreign key management automatically when you query related data, and can also auto-generate migrations reflecting schema changes.
const { DataTypes } = require('sequelize');
const User = sequelize.define('User', {
name: { type: DataTypes.STRING, allowNull: false },
email: { type: DataTypes.STRING, unique: true },
});
const Post = sequelize.define('Post', { title: DataTypes.STRING });
User.hasMany(Post);
Post.belongsTo(User);
const userWithPosts = await User.findByPk(1, { include: Post });Real-world example A blogging platform defines User and Post Sequelize models with a hasMany/belongsTo relationship, letting the application fetch a user along with all their posts in a single query via { include: Post }, without needing to hand-write the underlying SQL JOIN.