sequelize / sequelize/sequelize

belongsToMany Association on the same model with a different foreign key and alias fails

Open
#8,263 25 comments 12 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Great SSCCE status: understood type: bug
Dominant language
TypeScript
Stars
30.4k
Forks
4.3k
Avg merge
1d 6h
Merged PRs (30d)
68

Description

What you are doing?

I have defined my association on the User model as follows

    User.belongsToMany(User, {
      through: models.Following,
      as: 'Follower',
      foreignKey: 'following_id',
    });

    User.belongsToMany(User, {
      through: models.Following,
      as: 'Following',
      foreignKey: 'follower_id',
    });

What do you expect to happen?

I did this so that I could then call user.GetFollower() and user.GetFollowing() functions. This worked fine with sequelize v3

What is actually happening?

With sequelize v4, I now get the error
SequelizeAssociationError: You have used the alias Following in two separate associations. Aliased associations must have unique aliases.

If I remove the second User.belongsToMany, it solves the problem but I am no longer able to use user.getFollowing() which returns as undefined.

Dialect: mysql
Database version: 5.7
Sequelize version: 4.8

P.S. I did check https://github.com/sequelize/sequelize/issues/7775. But it is not applicable to my case. I do not have the Model.associate(models) being called multiple times. I have it called only once - in the index.js file that sequelize-cli generated.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the two User.belongsToMany(User) definitions and the sequelize-cli-generated index.js association setup. Reproduce the alias error with Sequelize 4.8 and MySQL 5.7, then inspect how the associations are registered. Done means both associations can coexist with distinct aliases and the corresponding getter methods are available.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mysql, node.js
Domain
backend-api-design, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.