【问题标题】:Sequelize many to many with extra columns用额外的列对多对多进行续集
【发布时间】:2017-01-17 10:59:17
【问题描述】:

经过一些研究,我没有发现任何与我的问题有关的东西。所以设置是一个 M:M 关系已经与 sequelize (sqllite) 一起工作:

return User.find({ where: { _id: userId } }).then(user => {
   logger.info(`UserController - found user`);
   Notification.find({ where: { _id: notificationId } }).then(notification => {
      if (associate) {
        return user.addNotification([notification]);
      } else {
        return user.removeNotification([notification]);
      }
   })
})

问题是我在 inter table(cityId, active) 中有额外的字段,我不知道在运行“addNotification”时如何更新它。

提前致谢

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    为了向数据透视表添加数据,您应该将数据作为添加函数的第二个参数传递

    user.addNotification(notification, {cityId: 1, active: true});
    

    【讨论】:

    • 请注意,API + 文档自此发生了变化,RPaul 的回答对 Sequelize v4+ 有效
    【解决方案2】:

    如果您使用的是 Sequelize 4.x 版,API 中会有一些变化

    关系添加/设置/创建设置器现在通过将属性作为 options.through 传递来设置它们(以前第二个参数用作通过属性,现在它考虑的选项是通过作为子选项)

    user.addNotification(notification, { through: {cityId: 1, active: true}});
    

    【讨论】:

      【解决方案3】:

      当连接表有附加属性时,这些可以在选项对象中传递:

      UserProject = sequelize.define('user_project', {
        role: Sequelize.STRING
      });
      User.belongsToMany(Project, { through: UserProject });
      Project.belongsToMany(User, { through: UserProject });
      // through is required!
      
      user.addProject(project, { through: { role: 'manager' }});
      

      您可以在此处找到更多相关信息:https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-29
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多