簡體   English   中英

僅在子表中進行插入插入(關聯:belongsTo)

[英]Sequelize Inserts only in child table (Association: belongsTo)

我有2個模型: UsersDoctors ,其中Doctors模型在Users上具有belongsTo()約束。

module.exports = (sequelize, DataTypes) => {
  const Doctors = sequelize.define('Doctors', {
    specialization: { type: DataTypes.STRING }
  })

  Doctors.associate = function (models) {
    Doctors.belongsTo(models.Users)
  }

  return Doctors
}

foreign key出現在我的數據庫中,並且CREATE TABLE已正確完成,但是

const newDoctor = await Doctors.create({
  specialization: req.body.specialization,
  Users: {
    firstname: firstname,
    lastname: lastname,
    email: email,
    password: password
  }
}, { include: Users })

發送請求時, 它會添加Doctors表中,但不會添加Users表中。

值得一提的是,所有關系都在另一個文件中完成,並且一切正常。

關於如何進行這項工作的任何想法?

編輯 :因此要清楚,Users表未填充 ,但Doctors已填充

有時,Sequelize需要您在關聯上指定一個別名。

Doctors.belongsTo(models.Users, { as: 'Users' })

並在創建時添加別名。

const newDoctor = await Doctors.create({
  specialization: req.body.specialization,
  Users: {
    firstname: firstname,
    lastname: lastname,
    email: email,
    password: password
  }
}, { include: { model: Users, as: 'Users'} }).

別名和對象上的名稱必須相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM