Sequelize.js 使用现有关联创建续集

Sequelize.js 使用现有关联创建续集,sequelize.js,Sequelize.js,如何使用对象创建具有现有关联的条目 比如说, User.create({ socialMedia: [{ socialId: 1, //should reference existing social media userSocialMedia: { name: 'foo' //should create new "through" entry } }], bank: { bankId: 1 //should reference exist

如何使用对象创建具有现有关联的条目

比如说,

User.create({
  socialMedia: [{
    socialId: 1, //should reference existing social media
    userSocialMedia: {
      name: 'foo' //should create new "through" entry
    }
  }],
  bank: {
    bankId: 1 //should reference existing bank
  });

我可以做
User.create({bankId:1})
,但是由于从客户端发送的数据是这种形式,有没有办法告诉sequelize是为每个包含的模型添加新的还是使用现有的?

一种方法是使用外键属性名并直接提供ID,而不是通过嵌套对象。 在您的示例中,联接列可能称为bankId

您可以将用户创建为:

{
  socialMedia: [{
    socialId: 1, //should reference existing social media
    userSocialMedia: {
      name: 'foo' //should create new "through" entry
    }
  }],
  bankId: 1 //should reference existing bank
}

github上的这个问题让我想到了这个解决方案: