Reputation: 371
I am designing a database schema for an application. It has two models.
User will be associated with a team in two ways
As an owner
Team.belongsTo(User, { foreignKey: "fk_ownerId" });
User.hasMany(Team, { foreignKey: "fk_ownerId" });
As a member
User.belongsToMany(Team, { through: 'TeamToUser' });
Team.belongsToMany(User, { through: 'TeamToUser' });
So this way I ended up having multiple associations between two models.
Is it a good practice to make multiple associations between two models or is there any other to design these two models so that I can fetch data efficiently and with minimal piece of code ?
Upvotes: 0
Views: 764
Reputation: 22758
All looks good except that you didn't indicate aliases for your associations. I strongly recommend you to do it in such cases:
Team.belongsTo(User, { foreignKey: "fk_ownerId", as: 'owner' });
User.hasMany(Team, { foreignKey: "fk_ownerId", as: 'ownedTeams' });
User.belongsToMany(Team, { through: 'TeamToUser', as: 'teams' });
Team.belongsToMany(User, { through: 'TeamToUser', as: 'members' });
Upvotes: 1