Sequelize join without association

Sequelize Join Without Association

When using Sequelize, you can perform joins between tables even without explicit associations defined in your models.

To perform a join without association, you can use the `query` method provided by Sequelize. This method allows you to write custom SQL queries and fetch the results into Sequelize models.

Here’s an example of how you can perform a join without association:

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

    // Define your models
    const User = connection.define('User', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      username: {
        type: DataTypes.STRING,
        allowNull: false
      }
    });

    const Post = connection.define('Post', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      title: {
        type: DataTypes.STRING,
        allowNull: false
      },
      userId: {
        type: DataTypes.INTEGER,
        allowNull: false
      }
    });

    // Perform the join query without association
    connection.query('SELECT * FROM Users INNER JOIN Posts ON Users.id = Posts.userId', { 
      model: [User, Post], 
      mapToModel: true 
    }).then(([users, posts]) => {
      // Access the fetched records
      console.log(users);
      console.log(posts);
    }).catch(error => {
      console.error('Error fetching records:', error);
    });
  

In the above example, we have two models: `User` and `Post`. We want to perform a join query to fetch all users and their associated posts.

The custom SQL query used in `connection.query` joins the `Users` and `Posts` tables using the foreign key relationship between them (`Users.id = Posts.userId`). The `model` and `mapToModel` options allow Sequelize to map the fetched records to the specified models.

Finally, the `then` block allows you to access the fetched records. In this example, `users` and `posts` will contain the fetched User and Post records, respectively.

This way, you can perform joins between tables in Sequelize even without explicit associations.

Same cateogry post

Leave a comment