使用现有关联创建Sequelize

时间:2016-07-17 12:16:31

标签: 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 existing bank
  });

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

1 个答案:

答案 0 :(得分:1)

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

您可以将用户创建为:

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