加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:08:28 所属栏目:百科 来源:网络整理
导读:我的 postgresql数据库中有2个模型,并使用sequelize和node: 用户 交易 并且像这样关联: UserModel.hasMany(TransactionModel,{ as: 'sentTransactions',foreignKey: 'senderId' });UserModel.hasMany(TransactionModel,{ as: 'receivedTransactions',forei
我的 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 }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读