sequelize
sequelize copied to clipboard
Bug with mixins when using with custom unique constraint in M:N relation
Issue Creation Checklist
- [x] I understand that my issue will be automatically closed if I don't fill in the requested information
- [x] I have read the contribution guidelines
Bug Description
The problem is that model mixins incorrectly interacts with unique constraints.
Let's say we have model A
and B
.
We need M:N relation between them.
We establish it throuh junction table C
.
This relation should contain additional boolean field flag
.
At our case we need to extend default unique constraint with this flag
i.e. uniqueness should be determined by three fields ( Aid, BId, flag)
.
To do this we have perform 2 steps:
- Turn off default constraint by passing
unique : false
insidebelongsToMany
relation definition. - Define our own unique combined key with both
AId
,BId
andflag
.
Now we suggest that we can relate A
with B
twice (but with different flag
value).
It works fine if we directly add two records inside C
:
const a = await A.create();
const b = await B.create();
await C.create({ 'Aid': a.Id, 'Bid': b.Id, 'flag': true });
await C.create({ 'Aid': a.Id, 'Bid': b.Id, 'flag': false }); // <- flag is different
console.log(await C.count()); // <- will display us 2 as expected
But if we do the same with the help of mixins addB
we'll get different output:
const a = await A.create();
const b = await B.create();
await a.addB(b, { through: {flag: true } });
await a.addB(b, { through: {flag: false } }); // <- same different values
console.log(await C.count()); // will display us 1 instead of 2.
Reproducible Example
Here is the link to the SSCCE for this issue: https://github.com/JaoodxD/sequelize-sscce-m-m-bug
What do you expect to happen?
When we turn off the unique constraint inside belongsToMany
declaration
mixin addB
should create two different records inside junction table C
.
What is actually happening?
Mixin addB
still check only (Aid, BId)
constraint and update previous record.
Environment
- Sequelize version: 6.21.3
- Node.js version: 18.5.0
- Database & Version: PostgreSQL 14.3
- Connector library & Version: [email protected]
Would you be willing to resolve this issue by submitting a Pull Request?
- [ ] Yes, I have the time and I know how to start.
- [x] Yes, I have the time but I will need guidance.
- [ ] No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
- [ ] No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.
Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.
👍