如何在 sequelize 中更新 through-NM-attribute?

How can I update a through-NM-attribute in sequelize?

我已经阅读了 个问题,但它对我没有帮助,所以我问自己:

假设我有 2 个 table 由 NM 通过 table 使用 Sequelize 和 MariaDB 加入:

User <-- UserItem --> Item

一个用户可以拥有多个物品,一个物品可以属于多个用户。但是我需要一个自定义的 through 属性来存储 Item 的数量,我们称它为 Apples。所以,根据 docs,这将是定义:

var UserItem = Sequelize.define('UserItem', {
  quantity: DataTypes.INTEGER
}, 
  timestamps: false
});
models.Item.belongsToMany(models.User, {through: 'UserItem'});
models.User.belongsToMany(models.Item, {through: 'UserItem'});

然后我添加一个与 through 属性的新关系,如下所示:

User.addItem(item, { quantity: 0 });

这按预期工作。但是,如果我需要更新项目的数量怎么办?我可以执行以下操作:

User.addItem(item, { quantity: 20 });

并且我的Item数量会在存在的情况下更新为20,否则插入。我不想要这个。我想要这样的东西:

User.addItem(item, { quantity: quantity + 1 });

但是由于无法查询联接 table,我无法获取特定的 NM 行以使用先前的值进行更新。

我怎样才能做到这一点?提前致谢。

您仍然有 docs 中指定的加入 table DAO。

在这种情况下,您需要知道 item 是否是新关联。

所以它看起来像。

User.hasItem( item )
    .then( exists => {

       if ( !exists ) { 
            return User.addItem( item, { quantity : 20 } ) 
       } else {
            item.UserItem.quantity += 1;
            return item.UserItem.save();
       }

    } )

您还可以阅读有关 hasAssociation in the docs 的更多信息。