sequelize / sequelize/sequelize
belongsToMany Association on the same model with a different foreign key and alias fails
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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