How to use sequelize many-to-many queries? [resolved]

Business background

there are three table relationships as follows:

  • Master Table teacher : id , name
  • Student Table student : id , name
  • teacher-student relationship table relation : id , teacher_id , student_id

the above three tables have established foreign key relationships in mysql

question

how to query all the student information corresponding to a teacher in sequelize ?
according to official documents, only two tables can be jointly queried, but it cannot be figured out if it involves three tables.

Code

db.teacher.hasMany(db.relation,{
    foreignKey:`teacher_id`
});
db.relation.hasMany(db.student,{
    foreignKey:`id`,
    targetKey:"student_id`
})
//???????????~~~
Mar.16,2021

that's what I did before:

@leftstick</a> <br><br>user----userId<br>topic ----topicId<br>:like <br>

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

this is where I query someone's topic of concern and get the details of the topic from topic. Such as title, description and so on.

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

results obtained

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

but the data I want is that the topics of concern are grouped into the topics array.

I would like to ask how to solve this situation?
2, or whether the table association I established is established with the following

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

many-to-many, establish a connection, how to manipulate this data?

Menu