Node.js: model relationships in Sequelize

Sequelize is an Object-Relational Mapping (ORM) for Node.js that simplifies interaction with relational databases such as MySQL, PostgreSQL, and SQLite. When working with databases, you often need to manage relationships between tables, and Sequelize offers an elegant way to do this. In this article, we will explore how to define and manage model relationships in Sequelize./p>

Definition of models

To start managing relationships between models, you need to define the models themselves. For example, let's say you need to manage a simple e-commerce application with two main entities: User and Product. Here's what Sequelize template definitions might look like for these entities:


const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
   dialect: 'mysql',
   host: 'localhost',
});

const User = sequelize.define('User', {
   username: {
     type: DataTypes.STRING,
     allowNull: false,
   },
   // Other fields of the User model
});

const Product = sequelize.define('Product', {
   name: {
     type: DataTypes.STRING,
     allowNull: false,
   },
   price: {
     type: DataTypes.DECIMAL(10, 2),
     allowNull: false,
   },
   // Other fields of the Product model
});

Definition of relationships

Once the templates are defined, you can define the relationships between them. In this case, we want to establish a relationship between User and Product, where a user can have many products and a product can be owned by only one user. This is a typical example of a one-to-many relationship.

To define this relationship, you need to use the Sequelize belongsTo and hasMany methods. Here's how to do it:


User.hasMany(Product, { as: 'products', foreignKey: 'userId' });
Product.belongsTo(User, { foreignKey: 'userId' });

In the code above, we are telling Sequelize that a user "has many" products, and a product "belongs to" a user. Additionally, we are specifying a foreign key userId that links the two models.

Examples of use

Now that we have defined the relationships, we can use them to execute complex queries involving both models. Here are some examples of how we might use these relationships:

Create a new user and associated products


const user = await User.create({
   username: 'john_doe',
});

const product1 = await Product.create({
   name: 'Smartphone',
   price: 599.99,
   userId: user.id,
});

const product2 = await Product.create({
   name: 'Laptop',
   price: 999.99,
   userId: user.id,
});

Find all of a user's products


const user = await User.findOne({ where: { username: 'john_doe' } });
const products = await user.getProducts();

Find the owner of a product


const product = await Product.findOne({ where: { name: 'Smartphone' } });
const owner = await product.getUser();

Conclusions

Sequelize greatly simplifies managing model relationships in a Node.js application. Using the hasMany and belongsTo methods, you can define complex relationships between database entities and query them intuitively. This is just one example of the many powerful features Sequelize offers to simplify the development of web applications based on relational databases.

Back to top