Sling Academy
Home/Node.js/Many to One Associations in Sequelize.js

Many to One Associations in Sequelize.js

Last updated: December 29, 2023

Overview

Understanding associations in Sequelize is crucial for establishing relationships between different data models in a Node.js application. The Many to One association is a fundamental component in relational databases, where many instances of a model can be associated with one instance of another model. This tutorial will guide you through the implementation of Many to One relationships in Sequelize, starting from setting up your models to querying your data effectively.

Setting Up

To begin with, let’s ensure Sequelize is installed, and we have a database to work with. Start by creating a new Node.js project and install Sequelize and the database driver of your choice (e.g., PostgreSQL, MySQL, SQLite).

npm init -y
npm install sequelize pg

Next, set up a new Sequelize instance:

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'postgres',
});

Defining Models

You’ll need at least two models to create a Many to One relationship. For instance, an ‘Order’ can belong to a single ‘Customer’, which means many orders can be associated with one customer.

const Customer = sequelize.define('customer', {
  name: Sequelize.STRING
});

const Order = sequelize.define('order', {
  item: Sequelize.STRING
});

Creating the Association

To associate these models, we can use Sequelize’s belongsTo and hasMany methods.

Order.belongsTo(Customer); // Many to One
Customer.hasMany(Order);   // One to Many

These methods will set up foreign keys and relational methods on your models.

Syncing the Models

With your associations defined, you need to sync your models with the database:

sequelize.sync({ force: true })
  .then(() => console.log('Models synchronized successfully.'))
  .catch((error) => console.error('Sync failed: ', error));

Advanced Usage

Sequelize also allows for more complex associations and interactions. You can specify foreign key constraints, set aliases, and customize the default behavior of your associations.

Order.belongsTo(Customer, {
  foreignKey: 'customerId',
  as: 'buyer'
});

This code snippet demonstrates setting a foreign key with a specific name and an alias for the association.

Querying Associated Data

With Sequelize, querying associated data is straightforward. You can use include to fetch associated models.

Order.findAll({
  include: [{
    model: Customer,
    as: 'buyer'
  }]
}).then(orders => {
  console.log(orders)
});

Conclusion

In this tutorial, we’ve covered the basics and some advanced techniques for working with Many to One relationships in Sequelize. Properly utilizing associations can significantly streamline your database operations and data management in Node.js applications. Experiment further to gain an even deeper understanding of Sequelize associations and their capabilities.

Next Article: Fixing error: sequelize.import is not a function in Node.js

Previous Article: Many to Many associations in Sequelize

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates