Search code examples
sequelize.jsassociations

Sequelize: One model many associations


I have a project with models User and Event where a user can have many events(one-to-many) and user can follow many events(many-to-many), i have the following associations:

User.hasMany(Event, {
  onDelete: "SET NULL",
  onUpdate: "CASCADE",
});
Event.belongsTo(User);

User.belongsToMany(Event, { through: "followedEvents" });
Event.belongsToMany(User, { through: "followedEvents" });

I want to use the built in method user.getEvents() to get the events a user follows from the joint many-to-many 'followedEvents' table. But when I do that it automatically gets the rows from the one-to-many table. Is there a way to specify which one i want to use?


Solution

  • You just need to use aliases for all such associationsin order to distinguish them later:

    User.hasMany(Event, {
      onDelete: "SET NULL",
      onUpdate: "CASCADE",
      as: 'events'
    });
    Event.belongsTo(User, { as: 'user' });
    
    User.belongsToMany(Event, { through: "followedEvents", as: 'follEvents' });
    Event.belongsToMany(User, { through: "followedEvents". as: 'follUsers' });
    

    That way you will have user.getEvents() and user.getFollEvents()