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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With