Wednesday, 7 June 2017

How to Create a Model and Initialize its Existing Associations?

I'm working with Sequelize and I finally have a great deal of my system working using the models and relationships it provides.

I have what I feel like I should have a relatively simple task that I want to complete.

I have a User model that has multiple models associated with it. The associations are defined in their respective model.js files and the associations are established between the models.

Now, when creating a user, I would like to go ahead and create corresponding entries for each of the user's associated models in the database. Currently, I'm achieving this through promise chaining, but then seems unwieldy and I feel like there must be a better way available.

Here is my User model:

'use strict';
module.exports = function (sequelize, DataTypes) {
    var User = sequelize.define('User', {
        name: DataTypes.STRING,
        bio: DataTypes.STRING,
        email: DataTypes.STRING,
        phoneNumber: DataTypes.STRING,
        accountType: DataTypes.STRING,
        location: DataTypes.STRING,
    }, {
        classMethods: {
            associate: function (models) {
                User.hasOne(models.SpecialData, {
                    foreignKey: 'userId',
                    as: 'specialData',
                });
            }
        }
    });
    return User;
};

and here is the associated data model:

'use strict';
module.exports = function (sequelize, DataTypes) {
    var SpecialData = sequelize.define('SpecialData', {
        special1: DataTypes.STRING,
        special2: DataTypes.STRING,
        special3: DataTypes.TEXT
    }, {
        classMethods: {
            associate: function (models) {
                // associations can be defined here
                SpecialData.belongsTo(models.User, {
                    foreignKey: 'userId',
                    onDelete: 'CASCADE',
                });
            }
        }
    });
    
    return SpecialData;
};

The associations are all established by looping through all of the models and calling associate on each of them.

Now, the promise chain approach I am taking now is working, but I've been trying to use the Sequelize example of creating/initializing associated models when creating the "parent" model. It uses the following approach:

return Product.create({
  title: 'Chair',
  user: {
    first_name: 'Mick',
    last_name: 'Broadstone',
    addresses: [{
      type: 'home',
      line_1: '100 Main St.',
      city: 'Austin',
      state: 'TX',
      zip: '78704'
    }]
  }
}, {
  include: [{
    association: Product.User,
    include: [ User.Addresses ]
  }]
});

Unfortunately, I can't seem to get make this work. I either run into a "cannot find table name error" or everything goes through, but no "SpecialData" is created.

Does anyone have any techniques or approaches to achieve this?



via Sam

No comments:

Post a Comment