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

Jur*_*rik 5 javascript sql orm node.js sequelize.js

我有两个与一对多关系的续集模型.我们称之为所有者和财产.

假设它们是使用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)
  }
}
Run Code Online (Sandbox Code Playgroud)

现在假设我想在我的数据库中插入所有者记录并插入一些属性记录以与所有者关联.我该怎么做呢?

我正在寻找类似的东西

Owner.create({name:'nice owner',
              property: [{name:'nice property'},
                         {name:'ugly property'}]});
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,我在Sequelize文档中找不到这个.

Rap*_*ack 15

您在创建所有者时无法关联属性现有记录,您必须在使用promise链后立即执行此操作.

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

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

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});
    });
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 我建议您的第三个“创建”示例也使用事务,否则如果属性的插入失败,您将陷入半成品所有者的困境。 (2认同)