Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize create with existing association

Tags:

sequelize.js

How to create entry with existing association by using object?

For example,

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
  });

I can do User.create({ bankId: 1 }), but since the data sent from client is in this form, is there a way to tell sequelize whether to add new or use existing for each included models?

like image 418
pbeta Avatar asked Jul 17 '16 12:07

pbeta


1 Answers

One way to do this is to use the foreign key property name and supply the ID directly rather than through the nested object. In your example, the join column is probably called bankId.

You could create your user as:

{
  socialMedia: [{
    socialId: 1, //should reference existing social media
    userSocialMedia: {
      name: 'foo' //should create new "through" entry
    }
  }],
  bankId: 1 //should reference existing bank
}
like image 169
bsyk Avatar answered Oct 20 '22 20:10

bsyk