微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 使用n:m和1:m关联的Sequelize delete实例并更新Model

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

>用户
>交易

并且像这样关联:

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',foreignKey: 'transactionId' });

这意味着用户有许多收到和发送的交易,每个用户可以“喜欢”许多交易.

如何删除事务并删除所有关联(接收者,发件人,liker)?我也不想删除用户.

我还想更新这样定义的用户模型,以便添加“email”属性

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,foreignKey: 'transactionId',onDelete: 'CASCADE' });

将电子邮件属性添加用户模型应该像这样简单:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐