简体   繁体   中英

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).

//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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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