sequelize / express-example

A proposal for the usage of Sequelize within an Express.JS application.
MIT License
2.5k stars 773 forks source link

What does Model.associate() do in model/index.js ? #95

Closed sdf611097 closed 4 years ago

sdf611097 commented 5 years ago

I'm curious what does associate() do in model/index.js

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

I try to print associate for my model, and all of them are undefined. So I'm curious why this example has these codes. http://docs.sequelizejs.com/class/lib/model.js~Model.html I try to find the definition from the doc, but I can't find it.

detonih commented 4 years ago

I have the same doubt.

remjx commented 4 years ago

I'm curious what does associate() do in model/index.js

If I recall correctly, associate is not a sequelize function, it is a function defined in the example code in each model. Check the model definition. I think that code is just there to simplify the initialization of all the models into the db variable.

papb commented 4 years ago

Hello everyone!

@markjackson02 is correct. That was an extra function defined in the old example code; it existed to allow associations to be defined after all models were defined themselves. It is basically resolving the following problem: 'how can we associate models while keeping each model in a separate file?' Since we obviously need the models defined before associating them, this gets slightly nontrivial. The old example used the strategy of defining an associate function on each model and calling this associate function for each model after all of them were defined.

I will update the new example soon with some associations, and will see if I work out another approach that might be less confusing.

papb commented 4 years ago

I will close this in favor of #106