Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  179] [ 1]  / answers: 1 / hits: 27822  / 8 Years ago, tue, june 14, 2016, 12:00:00

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.


More From » sql

 Answers
27

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


[#61777] Saturday, June 11, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;