Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize query on join table

Tags:

I am trying to querying a join table using sequelize: Here is the model:

db.client.belongsToMany(db.user, {
  through: db.clientUser,
   onDelete: 'cascade',
});
db.user.belongsToMany(db.client, {
   through: db.clientUser,
 });

and this is what I am trying to do:

db.user.findAll({
      where: {
        group_id: 1,
      },
      include: [{
        model: db.clientUser,
        where: {
          is_manager: 1,
        }
      }],
      raw: true,
    })

However I get the following error: client_user is not associated to user!

Any idea what could be the cause of this issue?

like image 309
mikey Avatar asked Nov 21 '17 03:11

mikey


People also ask

How do you query a JOIN table in Sequelize?

There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.

How do I JOIN two tables in node JS?

Join Two or More Tables You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.

How do I JOIN a Sequelize in node JS?

To make join queries using Sequelize on Node. js, we can use the include option with findAll . const posts = await Posts. findAll({ include: [{ model: User, required: true }] }) //...

How does include work in Sequelize?

To wrap up, include takes an array of objects. These objects are queries of their own, essentially just Sequelize queries within our main query. Inside each include query we specify the associated model , narrow our results with where , and alias our returned rows with as .


1 Answers

You declared a relationship between client from user through clientUser. Although pedantic, its complaint is technically correct: there is no explicitly declared relationship declared between client and clientUser. Nor should there be: your belongsToMany relationship should take care of that. Your query can be adjusted to work with this relationship.

Note: I don't know what tables group_id and is_manager are found in. They may need to be shuffled around.

db.user.findAll({
  where: {
    group_id: 1,
  },
  include: [{
    model: db.client,
    through: {
      where: {
        is_manager: 1, // Assuming clientUser.is_manager?
      },
    }],
  raw: true,
})
like image 139
spamguy Avatar answered Oct 11 '22 16:10

spamguy