繁体   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