我有一个用户orm与一个具有类似的方orm关联
public getParties!: HasManyGetAssociationsMixin<Party>;
public addParty!: HasManyAddAssociationMixin<Party, number>;
public hasParty!: HasManyHasAssociationMixin<Party, number>;
public countParties!: HasManyCountAssociationsMixin;
public removeParty!: HasManyRemoveAssociationMixin<Party, number>;
关联看起来像这个
User.belongsToMany(Party, { through: { model: 'UserParties', paranoid: true }, as: 'Parties' });
当我想添加派对或删除派对时,它非常有效,但是,如果我在删除派对后尝试添加它,它就不起作用了。
这个,不起作用
user.addParty(party) // works
user.removeParty(party) // works
user.addParty(party) // Doesn't work
我得到了这个错误:
ERROR: duplicate key value violates unique constraint "UserParties_pkey"
DETAIL: Key ("UserId", "PartyId")=(1, 1) already exists.
我知道我为什么会出现这个错误,但如果它存在但有一个deleted_at,我该如何使它覆盖它?
有两种方法:
- 不使用
paranoid
模式 - 将
deletedAt
包含到具有所有三个字段的唯一约束/索引中:UserId
、PartyId
和deletedAt
Sequelize不支持关联中的复合PK。您需要添加一个单独的自动生成字段作为PK