鍍金池/ 問答/數據庫/ sequelize多對多查詢怎么用?[已解決]

sequelize多對多查詢怎么用?[已解決]

業(yè)務背景

有三張表關系如下:

  • 老師表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`
})
//接下來怎么做???????????~~~
回答
編輯回答
不將就

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

多對多,建立聯系,怎么操作這數據呀?

2018年7月5日 06:40
編輯回答
舊顏

我之前是這么做的:

//定義從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"
  }
})
祝你成功!
2017年4月29日 10:31
編輯回答
淺時光

樓主請問一下,多對多關系中你是如何添加數據的?
如果需要添加一個學生,老師的數據已經存在了。如何添加這個學生和學生與老師的關系

2018年1月9日 20:13