Advanced M:N Associations

Make sure you have read the associations guide before reading this guide.

Let’s start with an example of a Many-to-Many relationship between User and Profile.

  1. const User = sequelize.define('user', {
  2. username: DataTypes.STRING,
  3. points: DataTypes.INTEGER
  4. }, { timestamps: false });
  5. const Profile = sequelize.define('profile', {
  6. name: DataTypes.STRING
  7. }, { timestamps: false });

The simplest way to define the Many-to-Many relationship is:

  1. User.belongsToMany(Profile, { through: 'User_Profiles' });
  2. Profile.belongsToMany(User, { through: 'User_Profiles' });

By passing a string to through above, we are asking Sequelize to automatically generate a model named User_Profiles as the through table (also known as junction table), with only two columns: userId and profileId. A composite unique key will be established on these two columns.

We can also define ourselves a model to be used as the through table.

  1. const User_Profile = sequelize.define('User_Profile', {}, { timestamps: false });
  2. User.belongsToMany(Profile, { through: User_Profile });
  3. Profile.belongsToMany(User, { through: User_Profile });

The above has the exact same effect. Note that we didn’t define any attributes on the User_Profile model. The fact that we passed it into a belongsToMany call tells sequelize to create the two attributes userId and profileId automatically, just like other associations also cause Sequelize to automatically add a column to one of the involved models.

However, defining the model by ourselves has several advantages. We can, for example, define more columns on our through table:

  1. const User_Profile = sequelize.define('User_Profile', {
  2. selfGranted: DataTypes.BOOLEAN
  3. }, { timestamps: false });
  4. User.belongsToMany(Profile, { through: User_Profile });
  5. Profile.belongsToMany(User, { through: User_Profile });

With this, we can now track an extra information at the through table, namely the selfGranted boolean. For example, when calling the user.addProfile() we can pass values for the extra columns using the through option.

Example:

  1. const amidala = await User.create({ username: 'p4dm3', points: 1000 });
  2. const queen = await Profile.create({ name: 'Queen' });
  3. await amidala.addProfile(queen, { through: { selfGranted: false } });
  4. const result = await User.findOne({
  5. where: { username: 'p4dm3' },
  6. include: Profile
  7. });
  8. console.log(result);

Output:

  1. {
  2. "id": 4,
  3. "username": "p4dm3",
  4. "points": 1000,
  5. "profiles": [
  6. {
  7. "id": 6,
  8. "name": "queen",
  9. "User_Profile": {
  10. "userId": 4,
  11. "profileId": 6,
  12. "selfGranted": false
  13. }
  14. }
  15. ]
  16. }

You can create all relationship in single create call too.

Example:

  1. const amidala = await User.create({
  2. username: 'p4dm3',
  3. points: 1000,
  4. profiles: [{
  5. name: 'Queen',
  6. User_Profile: {
  7. selfGranted: true
  8. }
  9. }]
  10. }, {
  11. include: Profile
  12. });
  13. const result = await User.findOne({
  14. where: { username: 'p4dm3' },
  15. include: Profile
  16. });
  17. console.log(result);

Output:

  1. {
  2. "id": 1,
  3. "username": "p4dm3",
  4. "points": 1000,
  5. "profiles": [
  6. {
  7. "id": 1,
  8. "name": "Queen",
  9. "User_Profile": {
  10. "selfGranted": true,
  11. "userId": 1,
  12. "profileId": 1
  13. }
  14. }
  15. ]
  16. }

You probably noticed that the User_Profiles table does not have an id field. As mentioned above, it has a composite unique key instead. The name of this composite unique key is chosen automatically by Sequelize but can be customized with the uniqueKey option:

  1. User.belongsToMany(Profile, { through: User_Profiles, uniqueKey: 'my_custom_unique' });

Another possibility, if desired, is to force the through table to have a primary key just like other standard tables. To do this, simply define the primary key in the model:

  1. const User_Profile = sequelize.define('User_Profile', {
  2. id: {
  3. type: DataTypes.INTEGER,
  4. primaryKey: true,
  5. autoIncrement: true,
  6. allowNull: false
  7. },
  8. selfGranted: DataTypes.BOOLEAN
  9. }, { timestamps: false });
  10. User.belongsToMany(Profile, { through: User_Profile });
  11. Profile.belongsToMany(User, { through: User_Profile });

The above will still create two columns userId and profileId, of course, but instead of setting up a composite unique key on them, the model will use its id column as primary key. Everything else will still work just fine.

Through tables versus normal tables and the “Super Many-to-Many association”

Now we will compare the usage of the last Many-to-Many setup shown above with the usual One-to-Many relationships, so that in the end we conclude with the concept of a “Super Many-to-Many relationship”.

Models recap (with minor rename)

To make things easier to follow, let’s rename our User_Profile model to grant. Note that everything works in the same way as before. Our models are:

  1. const User = sequelize.define('user', {
  2. username: DataTypes.STRING,
  3. points: DataTypes.INTEGER
  4. }, { timestamps: false });
  5. const Profile = sequelize.define('profile', {
  6. name: DataTypes.STRING
  7. }, { timestamps: false });
  8. const Grant = sequelize.define('grant', {
  9. id: {
  10. type: DataTypes.INTEGER,
  11. primaryKey: true,
  12. autoIncrement: true,
  13. allowNull: false
  14. },
  15. selfGranted: DataTypes.BOOLEAN
  16. }, { timestamps: false });

We established a Many-to-Many relationship between User and Profile using the Grant model as the through table:

  1. User.belongsToMany(Profile, { through: Grant });
  2. Profile.belongsToMany(User, { through: Grant });

This automatically added the columns userId and profileId to the Grant model.

Note: As shown above, we have chosen to force the grant model to have a single primary key (called id, as usual). This is necessary for the Super Many-to-Many relationship that will be defined soon.

Using One-to-Many relationships instead

Instead of setting up the Many-to-Many relationship defined above, what if we did the following instead?

  1. // Setup a One-to-Many relationship between User and Grant
  2. User.hasMany(Grant);
  3. Grant.belongsTo(User);
  4. // Also setup a One-to-Many relationship between Profile and Grant
  5. Profile.hasMany(Grant);
  6. Grant.belongsTo(Profile);

The result is essentially the same! This is because User.hasMany(Grant) and Profile.hasMany(Grant) will automatically add the userId and profileId columns to Grant, respectively.

This shows that one Many-to-Many relationship isn’t very different from two One-to-Many relationships. The tables in the database look the same.

The only difference is when you try to perform an eager load with Sequelize.

  1. // With the Many-to-Many approach, you can do:
  2. User.findAll({ include: Profile });
  3. Profile.findAll({ include: User });
  4. // However, you can't do:
  5. User.findAll({ include: Grant });
  6. Profile.findAll({ include: Grant });
  7. Grant.findAll({ include: User });
  8. Grant.findAll({ include: Profile });
  9. // On the other hand, with the double One-to-Many approach, you can do:
  10. User.findAll({ include: Grant });
  11. Profile.findAll({ include: Grant });
  12. Grant.findAll({ include: User });
  13. Grant.findAll({ include: Profile });
  14. // However, you can't do:
  15. User.findAll({ include: Profile });
  16. Profile.findAll({ include: User });
  17. // Although you can emulate those with nested includes, as follows:
  18. User.findAll({
  19. include: {
  20. model: Grant,
  21. include: Profile
  22. }
  23. }); // This emulates the `User.findAll({ include: Profile })`, however
  24. // the resulting object structure is a bit different. The original
  25. // structure has the form `user.profiles[].grant`, while the emulated
  26. // structure has the form `user.grants[].profiles[]`.

The best of both worlds: the Super Many-to-Many relationship

We can simply combine both approaches shown above!

  1. // The Super Many-to-Many relationship
  2. User.belongsToMany(Profile, { through: Grant });
  3. Profile.belongsToMany(User, { through: Grant });
  4. User.hasMany(Grant);
  5. Grant.belongsTo(User);
  6. Profile.hasMany(Grant);
  7. Grant.belongsTo(Profile);

This way, we can do all kinds of eager loading:

  1. // All these work:
  2. User.findAll({ include: Profile });
  3. Profile.findAll({ include: User });
  4. User.findAll({ include: Grant });
  5. Profile.findAll({ include: Grant });
  6. Grant.findAll({ include: User });
  7. Grant.findAll({ include: Profile });

We can even perform all kinds of deeply nested includes:

  1. User.findAll({
  2. include: [
  3. {
  4. model: Grant,
  5. include: [User, Profile]
  6. },
  7. {
  8. model: Profile,
  9. include: {
  10. model: User,
  11. include: {
  12. model: Grant,
  13. include: [User, Profile]
  14. }
  15. }
  16. }
  17. ]
  18. });

Aliases and custom key names

Similarly to the other relationships, aliases can be defined for Many-to-Many relationships.

Before proceeding, please recall the aliasing example for belongsTo on the associations guide. Note that, in that case, defining an association impacts both the way includes are done (i.e. passing the association name) and the name Sequelize chooses for the foreign key (in that example, leaderId was created on the Ship model).

Defining an alias for a belongsToMany association also impacts the way includes are performed:

  1. Product.belongsToMany(Category, { as: 'groups', through: 'product_categories' });
  2. Category.belongsToMany(Product, { as: 'items', through: 'product_categories' });
  3. // [...]
  4. await Product.findAll({ include: Category }); // This doesn't work
  5. await Product.findAll({ // This works, passing the alias
  6. include: {
  7. model: Category,
  8. as: 'groups'
  9. }
  10. });
  11. await Product.findAll({ include: 'groups' }); // This also works

However, defining an alias here has nothing to do with the foreign key names. The names of both foreign keys created in the through table are still constructed by Sequelize based on the name of the models being associated. This can readily be seen by inspecting the generated SQL for the through table in the example above:

  1. CREATE TABLE IF NOT EXISTS `product_categories` (
  2. `createdAt` DATETIME NOT NULL,
  3. `updatedAt` DATETIME NOT NULL,
  4. `productId` INTEGER NOT NULL REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  5. `categoryId` INTEGER NOT NULL REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  6. PRIMARY KEY (`productId`, `categoryId`)
  7. );

We can see that the foreign keys are productId and categoryId. To change these names, Sequelize accepts the options foreignKey and otherKey respectively (i.e., the foreignKey defines the key for the source model in the through relation, and otherKey defines it for the target model):

  1. Product.belongsToMany(Category, {
  2. through: 'product_categories',
  3. foreignKey: 'objectId', // replaces `productId`
  4. otherKey: 'typeId' // replaces `categoryId`
  5. });
  6. Category.belongsToMany(Product, {
  7. through: 'product_categories',
  8. foreignKey: 'typeId', // replaces `categoryId`
  9. otherKey: 'objectId' // replaces `productId`
  10. });

Generated SQL:

  1. CREATE TABLE IF NOT EXISTS `product_categories` (
  2. `createdAt` DATETIME NOT NULL,
  3. `updatedAt` DATETIME NOT NULL,
  4. `objectId` INTEGER NOT NULL REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  5. `typeId` INTEGER NOT NULL REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  6. PRIMARY KEY (`objectId`, `typeId`)
  7. );

As shown above, when you define a Many-to-Many relationship with two belongsToMany calls (which is the standard way), you should provide the foreignKey and otherKey options appropriately in both calls. If you pass these options in only one of the calls, the Sequelize behavior will be unreliable.

Self-references

Sequelize supports self-referential Many-to-Many relationships, intuitively:

  1. Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
  2. // This will create the table PersonChildren which stores the ids of the objects.

Specifying attributes from the through table

By default, when eager loading a many-to-many relationship, Sequelize will return data in the following structure (based on the first example in this guide):

  1. // User.findOne({ include: Profile })
  2. {
  3. "id": 4,
  4. "username": "p4dm3",
  5. "points": 1000,
  6. "profiles": [
  7. {
  8. "id": 6,
  9. "name": "queen",
  10. "grant": {
  11. "userId": 4,
  12. "profileId": 6,
  13. "selfGranted": false
  14. }
  15. }
  16. ]
  17. }

Notice that the outer object is an User, which has a field called profiles, which is a Profile array, such that each Profile comes with an extra field called grant which is a Grant instance. This is the default structure created by Sequelize when eager loading from a Many-to-Many relationship.

However, if you want only some of the attributes of the through table, you can provide an array with the attributes you want in the attributes option. For example, if you only want the selfGranted attribute from the through table:

  1. User.findOne({
  2. include: {
  3. model: Profile,
  4. through: {
  5. attributes: ['selfGranted']
  6. }
  7. }
  8. });

Output:

  1. {
  2. "id": 4,
  3. "username": "p4dm3",
  4. "points": 1000,
  5. "profiles": [
  6. {
  7. "id": 6,
  8. "name": "queen",
  9. "grant": {
  10. "selfGranted": false
  11. }
  12. }
  13. ]
  14. }

If you don’t want the nested grant field at all, use attributes: []:

  1. User.findOne({
  2. include: {
  3. model: Profile,
  4. through: {
  5. attributes: []
  6. }
  7. }
  8. });

Output:

  1. {
  2. "id": 4,
  3. "username": "p4dm3",
  4. "points": 1000,
  5. "profiles": [
  6. {
  7. "id": 6,
  8. "name": "queen"
  9. }
  10. ]
  11. }

If you are using mixins (such as user.getProfiles()) instead of finder methods (such as User.findAll()), you have to use the joinTableAttributes option instead:

  1. someUser.getProfiles({ joinTableAttributes: ['selfGranted'] });

Output:

  1. [
  2. {
  3. "id": 6,
  4. "name": "queen",
  5. "grant": {
  6. "selfGranted": false
  7. }
  8. }
  9. ]

Many-to-many-to-many relationships and beyond

Consider you are trying to model a game championship. There are players and teams. Teams play games. However, players can change teams in the middle of the championship (but not in the middle of a game). So, given one specific game, there are certain teams participating in that game, and each of these teams has a set of players (for that game).

So we start by defining the three relevant models:

  1. const Player = sequelize.define('Player', { username: DataTypes.STRING });
  2. const Team = sequelize.define('Team', { name: DataTypes.STRING });
  3. const Game = sequelize.define('Game', { name: DataTypes.INTEGER });

Now, the question is: how to associate them?

First, we note that:

  • One game has many teams associated to it (the ones that are playing that game);
  • One team may have participated in many games.

The above observations show that we need a Many-to-Many relationship between Game and Team. Let’s use the Super Many-to-Many relationship as explained earlier in this guide:

  1. // Super Many-to-Many relationship between Game and Team
  2. const GameTeam = sequelize.define('GameTeam', {
  3. id: {
  4. type: DataTypes.INTEGER,
  5. primaryKey: true,
  6. autoIncrement: true,
  7. allowNull: false
  8. }
  9. });
  10. Team.belongsToMany(Game, { through: GameTeam });
  11. Game.belongsToMany(Team, { through: GameTeam });
  12. GameTeam.belongsTo(Game);
  13. GameTeam.belongsTo(Team);
  14. Game.hasMany(GameTeam);
  15. Team.hasMany(GameTeam);

The part about players is trickier. We note that the set of players that form a team depends not only on the team (obviously), but also on which game is being considered. Therefore, we don’t want a Many-to-Many relationship between Player and Team. We also don’t want a Many-to-Many relationship between Player and Game. Instead of associating a Player to any of those models, what we need is an association between a Player and something like a “team-game pair constraint”, since it is the pair (team plus game) that defines which players belong there. So what we are looking for turns out to be precisely the junction model, GameTeam, itself! And, we note that, since a given game-team pair specifies many players, and on the other hand that the same player can participate of many game-team pairs, we need a Many-to-Many relationship between Player and GameTeam!

To provide the greatest flexibility, let’s use the Super Many-to-Many relationship construction here again:

  1. // Super Many-to-Many relationship between Player and GameTeam
  2. const PlayerGameTeam = sequelize.define('PlayerGameTeam', {
  3. id: {
  4. type: DataTypes.INTEGER,
  5. primaryKey: true,
  6. autoIncrement: true,
  7. allowNull: false
  8. }
  9. });
  10. Player.belongsToMany(GameTeam, { through: PlayerGameTeam });
  11. GameTeam.belongsToMany(Player, { through: PlayerGameTeam });
  12. PlayerGameTeam.belongsTo(Player);
  13. PlayerGameTeam.belongsTo(GameTeam);
  14. Player.hasMany(PlayerGameTeam);
  15. GameTeam.hasMany(PlayerGameTeam);

The above associations achieve precisely what we want. Here is a full runnable example of this:

  1. const { Sequelize, Op, Model, DataTypes } = require('sequelize');
  2. const sequelize = new Sequelize('sqlite::memory:', {
  3. define: { timestamps: false } // Just for less clutter in this example
  4. });
  5. const Player = sequelize.define('Player', { username: DataTypes.STRING });
  6. const Team = sequelize.define('Team', { name: DataTypes.STRING });
  7. const Game = sequelize.define('Game', { name: DataTypes.INTEGER });
  8. // We apply a Super Many-to-Many relationship between Game and Team
  9. const GameTeam = sequelize.define('GameTeam', {
  10. id: {
  11. type: DataTypes.INTEGER,
  12. primaryKey: true,
  13. autoIncrement: true,
  14. allowNull: false
  15. }
  16. });
  17. Team.belongsToMany(Game, { through: GameTeam });
  18. Game.belongsToMany(Team, { through: GameTeam });
  19. GameTeam.belongsTo(Game);
  20. GameTeam.belongsTo(Team);
  21. Game.hasMany(GameTeam);
  22. Team.hasMany(GameTeam);
  23. // We apply a Super Many-to-Many relationship between Player and GameTeam
  24. const PlayerGameTeam = sequelize.define('PlayerGameTeam', {
  25. id: {
  26. type: DataTypes.INTEGER,
  27. primaryKey: true,
  28. autoIncrement: true,
  29. allowNull: false
  30. }
  31. });
  32. Player.belongsToMany(GameTeam, { through: PlayerGameTeam });
  33. GameTeam.belongsToMany(Player, { through: PlayerGameTeam });
  34. PlayerGameTeam.belongsTo(Player);
  35. PlayerGameTeam.belongsTo(GameTeam);
  36. Player.hasMany(PlayerGameTeam);
  37. GameTeam.hasMany(PlayerGameTeam);
  38. (async () => {
  39. await sequelize.sync();
  40. await Player.bulkCreate([
  41. { username: 's0me0ne' },
  42. { username: 'empty' },
  43. { username: 'greenhead' },
  44. { username: 'not_spock' },
  45. { username: 'bowl_of_petunias' }
  46. ]);
  47. await Game.bulkCreate([
  48. { name: 'The Big Clash' },
  49. { name: 'Winter Showdown' },
  50. { name: 'Summer Beatdown' }
  51. ]);
  52. await Team.bulkCreate([
  53. { name: 'The Martians' },
  54. { name: 'The Earthlings' },
  55. { name: 'The Plutonians' }
  56. ]);
  57. // Let's start defining which teams were in which games. This can be done
  58. // in several ways, such as calling `.setTeams` on each game. However, for
  59. // brevity, we will use direct `create` calls instead, referring directly
  60. // to the IDs we want. We know that IDs are given in order starting from 1.
  61. await GameTeam.bulkCreate([
  62. { GameId: 1, TeamId: 1 }, // this GameTeam will get id 1
  63. { GameId: 1, TeamId: 2 }, // this GameTeam will get id 2
  64. { GameId: 2, TeamId: 1 }, // this GameTeam will get id 3
  65. { GameId: 2, TeamId: 3 }, // this GameTeam will get id 4
  66. { GameId: 3, TeamId: 2 }, // this GameTeam will get id 5
  67. { GameId: 3, TeamId: 3 } // this GameTeam will get id 6
  68. ]);
  69. // Now let's specify players.
  70. // For brevity, let's do it only for the second game (Winter Showdown).
  71. // Let's say that that s0me0ne and greenhead played for The Martians, while
  72. // not_spock and bowl_of_petunias played for The Plutonians:
  73. await PlayerGameTeam.bulkCreate([
  74. // In 'Winter Showdown' (i.e. GameTeamIds 3 and 4):
  75. { PlayerId: 1, GameTeamId: 3 }, // s0me0ne played for The Martians
  76. { PlayerId: 3, GameTeamId: 3 }, // greenhead played for The Martians
  77. { PlayerId: 4, GameTeamId: 4 }, // not_spock played for The Plutonians
  78. { PlayerId: 5, GameTeamId: 4 } // bowl_of_petunias played for The Plutonians
  79. ]);
  80. // Now we can make queries!
  81. const game = await Game.findOne({
  82. where: {
  83. name: "Winter Showdown"
  84. },
  85. include: {
  86. model: GameTeam,
  87. include: [
  88. {
  89. model: Player,
  90. through: { attributes: [] } // Hide unwanted `PlayerGameTeam` nested object from results
  91. },
  92. Team
  93. ]
  94. }
  95. });
  96. console.log(`Found game: "${game.name}"`);
  97. for (let i = 0; i < game.GameTeams.length; i++) {
  98. const team = game.GameTeams[i].Team;
  99. const players = game.GameTeams[i].Players;
  100. console.log(`- Team "${team.name}" played game "${game.name}" with the following players:`);
  101. console.log(players.map(p => `--- ${p.username}`).join('\n'));
  102. }
  103. })();

Output:

  1. Found game: "Winter Showdown"
  2. - Team "The Martians" played game "Winter Showdown" with the following players:
  3. --- s0me0ne
  4. --- greenhead
  5. - Team "The Plutonians" played game "Winter Showdown" with the following players:
  6. --- not_spock
  7. --- bowl_of_petunias

So this is how we can achieve a many-to-many-to-many relationship between three models in Sequelize, by taking advantage of the Super Many-to-Many relationship technique!

This idea can be applied recursively for even more complex, many-to-many-to-…-to-many relationships (although at some point queries might become slow).