Basic Joins in Sequelize

Sequelize makes it easy to work with related database tables. Often, a table is connected to another, and fetching related data requires a join. This article explains how to perform basic joins in Sequelize using simple associations.

1. Setting up models Consider two tables: User and Invoice.

A user can have many invoices, and each invoice belongs to one user.

const { Sequelize, DataTypes } = require(“sequelize”); const sequelize = new Sequelize(“database”, “user”, “password”, { dialect: “mysql” }); const User = sequelize.define(“User”, { name: DataTypes.STRING });

const Invoice = sequelize.define(“Invoice”, { amount: DataTypes.FLOAT });

// Define associations User.hasMany(Invoice); Invoice.belongsTo(User); Relationships: • User → Invoice

2. Using include for a join

Once associations are defined, include can fetch related data: const users = await User.findAll({ include: Invoice, }); console.log(JSON.stringify(users, null, 2));

Sequelize generates a SQL query similar to: SELECT `User`.`id`, `User`.`name`, `Invoices`.`id` AS `Invoices.id`, `Invoices`.`amount` AS `Invoices.amount` FROM `Users` AS `User` LEFT OUTER JOIN `Invoices` AS `Invoices` ON `User`.`id` = `Invoices`.`UserId`; By default, this is a LEFT OUTER JOIN, meaning all users are returned, even those without invoices.

3. INNER JOIN with required: true To return only users with invoices, add required: true: const usersWithInvoices = await User.findAll({ include: { model: Invoice, required: true, }, }); This produces an INNER JOIN, showing only users who have at least one invoice.

4. Viewing joined data

The result includes nested invoice data: [ { “id”: 1, “name”: “Alice”, “Invoices”: [ { “id”: 101, “amount”: 300.5 }, { “id”: 102, “amount”: 120.0 } ] }, { “id”: 2, “name”: “Bob”, “Invoices”: [] } ] With required: true, Bob would not appear since he has no invoices.

5. Summary

• Sequelize joins tables automatically using include.

• Default join type is LEFT OUTER JOIN; use required: true for INNER JOIN.

• Relationships must be defined with hasMany, belongsTo, etc.

• Joined data is returned as nested JSON.

Leave a comment

Your email address will not be published. Required fields are marked *