简体   繁体   English

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

[英]Sequelize.js insert a model with one-to-many relationship

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).假设它们是使用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)
  }
}

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.令人惊讶的是,我在 Sequelize 文档中找不到这个。

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请参阅http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM