sequelize多对多查询怎么用?[已解决]

业务背景

有三张表关系如下:

  • 老师表teacher:id,name
  • 学生表student:id,name
  • 老师学生关系表relation:id,teacher_id,student_id

以上三张表已经在mysql中建立好了外键关系

问题

sequelize里面怎么查询某个老师对应的所有学生信息呢?
根据官方文档的来,只能查进行两个表的联合查询,这涉及到3个表的,就搞不出来啦......

代码

db.teacher.hasMany(db.relation,{
    foreignKey:`teacher_id`
});
db.relation.hasMany(db.student,{
    foreignKey:`id`,
    targetKey:'student_id`
})
//接下来怎么做???????????~~~
阅读 5.7k
3 个回答

我之前是这么做的:

//定义从teacher到student的关联关系
db.teacher.belongsToMany(db.student, {
  through: db.relation,
  foreignKey: 'teacher_id'
})

//定义从student到teacher的关联关系
db.student.belongsToMany(db.teacher, {
  through: db.relation,
  foreignKey: 'student_id'
})

//查询teacher表,指定一个teacher id
db.teacher.findAll({
  include: [
    {
      model: db.student
    }
  ],
  where: {
    id: "某一个teacher id"
  }
})
祝你成功!

@leftstick
向你请教一个问题。
我有个用户表,user----userId
有个话题表,topic ----topicId
现在做一个关注表,就是用户关注了某一些话题:like
目前我的解决方案是,额外建立一张表

const like = Model.define('like', {
  userId: {
    type: sequelize.INTEGER,
    allowNull: true,
  },
  topicId:{
    type: sequelize.INTEGER,
    allowNull: false
  }
}, {
  tableName: 'like',
  timestamps: true,
  updatedAt: false
})

like.hasMany(Topic,{foreignKey:'topicId',sourceKey:'topicId'})

这是我查询某个人的关注话题,并且从topic中获取话题的详细信息。比如title,描述等等。。。

await LikeModel.findAll({
        include:{
          model:TopicModel,
        },
        attributes:{exclude:['id','createdAt']}
      }).then(res=>{
        console.log(res)
        ctx.body = res
      })

得到的结果

[
    {
        "userId": "1",
        "topicId": 1,
        "topics": [
            {
                "topicId": 1,
                "title": "1212",
                "des": "2332"
            }
        ]
    },
    {
        "userId": "1",
        "topicId": 2,
        "topics": [
            {
                "topicId": 2,
                "title": "1212",
                "des": "2332"
            }
        ]
    }
]

但我想要的数据是,关注的话题套入到topics这个数组中。。。

我想请问在这种情况如何解决呢??
2,或者我建立的表关联是否用如下建立

User.belongsToMany(Topic,{through:'like',foreignKey:'unionId',otherKey:'topicId'})
Topic.belongsToMany(User,{through:'like',foreignKey:'topicId',otherKey:'unionId'})

多对多,建立联系,怎么操作这数据呀?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进