'Adding an association ( HasManyAddAssociationMixin ) after deleting it with { paranoid: true }
I have a user orm associated with a party orm that has something like this
public getParties!: HasManyGetAssociationsMixin<Party>;
public addParty!: HasManyAddAssociationMixin<Party, number>;
public hasParty!: HasManyHasAssociationMixin<Party, number>;
public countParties!: HasManyCountAssociationsMixin;
public removeParty!: HasManyRemoveAssociationMixin<Party, number>;
The association looks like this
User.belongsToMany(Party, { through: { model: 'UserParties', paranoid: true }, as: 'Parties' });
and it works perfectly when I want to addParty or removeParty, But, If I try adding a party after having removed it, it doesn't work.
This, doesn't work
user.addParty(party) // works
user.removeParty(party) // works
user.addParty(party) // Doesn't work
I got this error:
ERROR: duplicate key value violates unique constraint "UserParties_pkey"
DETAIL: Key ("UserId", "PartyId")=(1, 1) already exists.
I know why I got this error, but how I can I make it so it overrides it, in the case it exists but has a deleted_at ?
Solution 1:[1]
There are two ways:
- don't use
paranoidmode - include
deletedAtto an unique constraint/index with all three fields:UserId,PartyIdanddeletedAt
Sequelize does not support a composite PK in associations. You need to add a separate autogenerated field as a PK
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
