Home > database >  Using sequelize-auto generates init-models.js. Is my app utilizing this for associations?
Using sequelize-auto generates init-models.js. Is my app utilizing this for associations?

Time:11-01

I'm working on an express rest api using sequelize. I successfully generated my models using sequelize-auto (which created init-models.js) and haven't thought about it since. My tables have associations and they show up in the init-models.js file but I can't seem to use query associating to utilize the associations.

Here's the init-models.js that sequelize-auto generated:

function initModels(sequelize) {
  ...

  product.belongsTo(manufacturer, { as: "manufacturer", foreignKey: "manufacturer_id" });
  manufacturer.hasMany(product, { as: "products", foreignKey: "manufacturer_id"});

  return { product, manufacturer }
}

module.exports = initModels;
module.exports.initModels = initModels;
module.exports.default = initModels

So my question is.. is this module getting loaded when my server starts and initializes everything? If not, could I just move my associations directly to the model init function as suggested in the documentation (I think I'd rather do this)?

CodePudding user response:

You'll get a better idea how to register and initialize models and their associations if you look at my other answer here.
As for shown generated code I suppose it would be better to call initModels inside the entry-point or a special DB module right after you have a Sequelize instance initialized to pass it to the function. And if you import this generated module then by default you will only have access to initModels to be able to call it wherever you wish to initialize models and to get them returned.

  • Related