Sequelize join without association

Sequelize Join Without Association

When using Sequelize, joins can be performed even without direct associations between the models. This can be achieved by explicitly specifying the join conditions using the `include` option in the query.

Let’s say we have two models – `User` and `Order`. A user can have multiple orders, but there is no direct association between these two models.

Example:

First, let’s define our models:


    const User = sequelize.define('User', {
      username: DataTypes.STRING,
      // other fields
    });
    
    const Order = sequelize.define('Order', {
      orderId: {
        type: DataTypes.INTEGER,
        primaryKey: true
      },
      // other fields
    });
  

Now, to perform a join between these models, we can use the following query:


    const userOrders = await User.findAll({
      attributes: ['username'],
      include: [
        {
          model: Order,
          attributes: ['orderId'],
          where: {
            // join condition
            userId: sequelize.col('User.id')
          }
        }
      ]
    });
  

In the above query, we specify the `include` option to join the `Order` model. We also specify the attributes we want to select from each model.

The `where` condition inside the `include` option specifies the join condition, where we match the `userId` field in the `Order` model with the `id` field in the `User` model.

The returned result will contain an array of `User` objects, each with an associated array of `Order` objects.

Read more interesting post

Leave a comment