Sequelize.js插入具有一对多关系的模型

我有两个具有一对多关系的sequelize模型。 我们称之为业主和财产。

假设它们是使用sails-hook-sequelize这样定义的(简化)。

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

现在假设我想在我的数据库中插入一个Ownerlogging,并插入一些属性logging来与所有者关联。 我该怎么做呢?

我正在寻找类似的东西

 Owner.create({name:'nice owner', property: [{name:'nice property'}, {name:'ugly property'}]}); 

令人惊讶的是,我无法在Sequelize文档中find它。

您不能在创build所有者时关联财产现有logging,您必须在承诺链之后执行此操作。

 Owner.create({name:'nice owner'}).then(function(owner){ owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/); }); 

为了避免这些关联(创build所有者,但某些关联失败)出现任何问题,最好使用事务。

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

但是,如果要创build与新属性关联的新所有者,您可以执行类似操作

 Owner.create({ name: 'nice owner', property: [ { name: 'nice property'}, { name: 'ugly property'} ] },{ include: [ Property] }); 

请参阅http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations