Sequelize.js insert a model with one-to-many relationship
You can't associate property existing records when you create the owner, you have to do that right after, with promise chain.
Owner.create({name:'nice owner'}).then(function(owner){
owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/);
});
To avoid any problems with those associations (owner created but some associations failed), it's better to use transactions.
sequelize.transaction(function(t) {
return Owner.create({name:'nice owner'}, {transaction: t}).then(function(owner){
return owner.setProperties([{name:'nice property'}, {name:'ugly property'}], {transaction : t});
});
});
However, if you want to create new Owner associated to new Properties you can do something like
Owner.create({
name: 'nice owner',
property: [
{ name: 'nice property'},
{ name: 'ugly property'}
]
},{
include: [ Property]
});
See http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations
Juraj Petrik
Updated on January 20, 2020Comments
-
Juraj Petrik over 4 years
I have two sequelize models with one-to-many relationship. Let's call them Owner and Property.
Assume they are defined using the sails-hook-sequelize as such (simplified).
//Owner.js module.exports = { options: { tableName: 'owner' }, attributes: { id: { type: Sequelize.BIGINT, allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: Sequelize.STRING(255) }, associations: function () { Owner.hasMany(Property, { foreignKey: { name: 'owner_id' } }); } } //Property.js module.exports = { options: { tableName: 'property' }, attributes: { id: { type: Sequelize.BIGINT, allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: Sequelize.STRING(255) } }
Now assume I want to insert an Owner record in my database and insert a few property records to associate with the owner. How do I do this?
I'm looking for something like
Owner.create({name:'nice owner', property: [{name:'nice property'}, {name:'ugly property'}]});
Surprisingly I can't find this in the Sequelize documentation.
-
diedu over 6 yearsI struggled some hours because the syntax was slighty different in the latest release, for anyone that can't make this work I recommend you to check out the integration tests to see how to use the create method in the most recent version github.com/sequelize/sequelize/blob/master/test/integration/…
-
Philipp Kyeck over 6 yearsI would recommend to also use a transaction for your third
create
example because otherwise if the INSERT of the properties fails you are stuck with the half-finished owner.