【问题标题】:How can I update a through-NM-attribute in sequelize?如何在 sequelize 中更新通过 NM 属性?
【发布时间】:2016-11-01 18:24:51
【问题描述】:

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

假设我有 2 个表,由 NM 通过使用 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 });

如果我的项目存在,我的数量将更新为 20,否则插入。我不想要这个。我想要这样的东西:

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

但由于无法对连接表进行查询,我无法使用之前的值获取特定的 NM 行进行更新。

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

【问题讨论】:

    标签: mysql node.js sequelize.js mariadb


    【解决方案1】:

    您仍然拥有docs 中指定的连接表 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 的更多信息。

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2017-08-01
      • 1970-01-01
      • 2016-12-04
      • 2011-09-16
      • 2014-09-13
      • 2020-12-24
      • 2019-10-09
      • 2017-08-08
      相关资源
      最近更新 更多