Associations help connect data models so they can work together. They show how one item relates to many others or belongs to one.
0
0
Associations (hasMany, belongsTo) in Express
Introduction
When you want to link users to their posts in a blog app.
When you need to connect orders to the customer who made them.
When you want to show all comments that belong to a single post.
When you want to organize products under categories.
When you want to fetch related data easily without writing complex queries.
Syntax
Express
ModelA.hasMany(ModelB, { foreignKey: 'modelAId' });
ModelB.belongsTo(ModelA, { foreignKey: 'modelAId' });hasMany means one item in ModelA can have many items in ModelB.
belongsTo means each item in ModelB belongs to one item in ModelA.
Examples
This links users to their posts. One user can have many posts.
Express
User.hasMany(Post, { foreignKey: 'userId' });
Post.belongsTo(User, { foreignKey: 'userId' });This connects products to categories. Each product belongs to one category.
Express
Category.hasMany(Product, { foreignKey: 'categoryId' });
Product.belongsTo(Category, { foreignKey: 'categoryId' });Sample Program
This example creates a User and two Posts linked to that user. Then it fetches all posts for the user and prints their titles.
Express
import express from 'express'; import { Sequelize, DataTypes } from 'sequelize'; const app = express(); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { name: DataTypes.STRING }); const Post = sequelize.define('Post', { title: DataTypes.STRING, content: DataTypes.TEXT, userId: DataTypes.INTEGER }); // Define associations User.hasMany(Post, { foreignKey: 'userId' }); Post.belongsTo(User, { foreignKey: 'userId' }); async function setup() { await sequelize.sync({ force: true }); const user = await User.create({ name: 'Alice' }); await Post.create({ title: 'Hello', content: 'First post', userId: user.id }); await Post.create({ title: 'World', content: 'Second post', userId: user.id }); const posts = await user.getPosts(); posts.forEach(post => { console.log(`${user.name} wrote: ${post.title}`); }); } setup();
OutputSuccess
Important Notes
Always define both sides of the association for clarity and easier queries.
Use the same foreign key name in both hasMany and belongsTo to link models correctly.
Sequelize automatically adds helper methods like getPosts() when associations are set.
Summary
Associations connect models to show relationships.
hasMany means one item has many related items.
belongsTo means one item belongs to another single item.