【问题标题】:Sequelize.js insert a model with one-to-many relationshipSequelize.js 插入具有一对多关系的模型
【发布时间】:2016-10-15 06:31:30
【问题描述】:

我有两个具有一对多关系的续集模型。我们称它们为所有者和财产。

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

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

我正在寻找类似的东西

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

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

【问题讨论】:

    标签: javascript sql node.js orm sequelize.js


    【解决方案1】:

    您不能在创建所有者时关联财产现有记录,您必须在之后立即使用承诺链进行关联。

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

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

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

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

    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

    【讨论】:

    • 我挣扎了几个小时,因为最新版本中的语法略有不同,对于无法完成这项工作的任何人,我建议您查看集成测试以了解如何使用 create 方法最新版本github.com/sequelize/sequelize/blob/master/test/integration/…
    • 我建议您也为您的第三个create 示例使用事务,否则如果属性的插入失败,您将被半成品所有者困住。
    猜你喜欢
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2011-07-21
    • 2014-05-20
    相关资源
    最近更新 更多