Course contentsShow
← Node.js
Lesson 793 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Relationships: One-to-Many Mappings

You will implement foreign key associations to establish hierarchical data structures.

Relationships: One-to-Many Mappings

In this lesson, you will learn how to structure your database to represent a relationship where a single record in one table can be associated with multiple records in another.

The Core Concept

A "One-to-Many" relationship is the most common association in database design. Think of a simple blog system: one User can write many Posts, but each Post is authored by exactly one User. To represent this in a relational database, we don't store a list of posts inside the user record. Instead, we use a foreign key.

We place a column in the posts table—typically named user_id—that points back to the id of the user who created it. This creates a bridge between the tables, allowing the database to enforce referential integrity.

Implementation Example

When using an ORM, we define this relationship in our model schemas to let the application understand how to join these tables automatically.

// User Model
const User = sequelize.define('User', {
  name: DataTypes.STRING
});

// Post Model
const Post = sequelize.define('Post', {
  title: DataTypes.STRING,
  user_id: DataTypes.INTEGER // The Foreign Key
});

// Establishing the association
User.hasMany(Post, { foreignKey: 'user_id' });
Post.belongsTo(User, { foreignKey: 'user_id' });

In this setup, the User.hasMany(Post) line tells your ORM that a single user instance is capable of owning multiple post instances. The Post.belongsTo(User) line creates the reciprocal link.

By defining these associations, you gain the ability to fetch related data easily. For example, you can query a user and "include" all their posts in a single operation. This structure keeps your data normalized and ensures that if a user is deleted, you can decide how to handle their associated posts—such as deleting them automatically or preventing the deletion to maintain data integrity.

Key Takeaway: A one-to-many relationship is implemented by adding a foreign key to the "many" side of the association, allowing you to link multiple child records to a single parent record.