gpt4 book ai didi

postgresql - 使用 n :m and 1:m associations and update Model 后续删除实例

转载 作者:行者123 更新时间:2023-11-29 11:29:54 24 4
gpt4 key购买 nike

我的 postgresql 数据库中有 2 个模型并使用 sequelize 和节点:

  1. 用户
  2. 交易

并且是这样关联的:

UserModel.hasMany(TransactionModel, { as: 'sentTransactions', foreignKey: 'senderId' });
UserModel.hasMany(TransactionModel, { as: 'receivedTransactions', foreignKey: 'receiverId' });
UserModel.belongsToMany(TransactionModel, { as: 'transactionLikes', through: 'UserLike', foreignKey: 'userId' });
TransactionModel.belongsTo(UserModel, { as: 'receiver' });
TransactionModel.belongsTo(UserModel, { as: 'sender' });
TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId' });

这意味着一个用户有很多接收和发送的交易,每个用户可以“喜欢”很多交易。

如何删除交易并删除所有关联(接收方、发送方、喜欢方)?我也不想删除用户。

我还想更新这样定义的用户模型,以添加“电子邮件”属性:

const UserModel = db.define('user', {
id: { type: Sequelize.STRING, unique: true, primaryKey: true },
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
username: {
type: Sequelize.STRING,
unique: {
args: true,
msg: USERNAME_IS_TAKEN,
},
}

如何更新模型?现有实例会怎样?

预先感谢您的帮助!

最佳答案

根据 this tutorial你的 M:N 关系应该像你期望的那样开箱即用:

For n:m, the default for both is CASCADE. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.

此外,要强制执行 CASCADE 行为,您还可以将 onDelete 选项传递给关联调用。像这样的东西应该可以解决问题:

TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId', onDelete: 'CASCADE' });

向用户模型添加电子邮件属性应该就这么简单:

const UserModel = db.define('user', {
id: {
type: Sequelize.STRING,
unique: true,
primaryKey: true
},
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
username: {
type: Sequelize.STRING,
unique: {
args: true,
msg: USERNAME_IS_TAKEN,
}
},
email: { type: Sequelize.STRING }
});

关于postgresql - 使用 n :m and 1:m associations and update Model 后续删除实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51473136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com