Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sdf611097 opened this issue Apr 8, 2019 · 4 comments
Closed

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

sdf611097 opened this issue Apr 8, 2019 · 4 comments

Comments

@sdf611097
Copy link

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
Copy link

detonih commented Apr 23, 2020

I have the same doubt.

@remjx
Copy link

remjx commented Apr 23, 2020

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
Copy link
Member

papb commented Jul 19, 2020

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
Copy link
Member

papb commented Jul 19, 2020

I will close this in favor of #106

@papb papb closed this as completed Jul 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants