Sequelize query on join table

馋奶兔 提交于 2019-12-10 19:59:33

问题


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?


回答1:


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,
})



回答2:


In order to perform joins, you have to specify in the model declaration the association of each model to other models you would like to perform join with. Associations like belongsTo, hasMany etc. Read all about it here



来源:https://stackoverflow.com/questions/47404648/sequelize-query-on-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!