As far as I can tell, using Sequelizejs, there does not seem to be a way to save object associations when the object itself is saved.
For example, I have a contact which can have 1 or more phoneNumber. Currently I have something like this for the association:
global.db.Contact.hasMany(global.db.PhoneNumber, {as: 'phoneNumbers'});
Using a rest endpoint I would like to post a new contact object (with any provided phone numbers) and save it to the database. My request object looks something like this:
{
firstName: "john",
lastName: "Doe",
phoneNumbers: [
{ number: "555-555-5555", type: "home" }
]
}
Right now I pass this object to build:
var contact = Contact.build(req.body);
And then call save (I know I could use create instead of build/save but we have custom logic in the save to track the modified data and which user did the modification)
contact.save();
This throws the following error which kind of makes sense.
column "phoneNumbers" of relation "Contacts" does not exist
The sql call is trying to set the value of a column "phoneNumbers" which does not exist. I obviously don't want it to do that... I really would like it to bulk create each phoneNumber in the array with the ID of the contact I am creating.
The only example I found was this: https://gist.github.com/sdepold/3040391 and I don't really want to have to do this... Since I coming from a rest endpoint, I would like a way to do this operation generically (I'll have many models with associations). I will also need to be able to do these operations in bulk (for importing contacts from other sources) so I would prefer that it be the minimal amount of sql calls. Has anyone found a good way to do this?
Sequelize v4 introduced a new feature which allows creation of an instance along with any associated instances.
In your case, it allows adding multiple phone number against a single user as provided below.
return Contact.create({
firstName: 'John',
lastName: 'Doe',
PhoneNumbers: [
{
number: '555-555-5555',
type: 'home'
},
{
number: '555-555-7777',
type: 'work'
}
]
}, {
include: [{
association: Product.PhoneNumber
}]
});
Detailed documentation can be found here Sequelize Docs - Creating with associations
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