【问题标题】:sequelize - how to update an association in n-m relation including join tablesequelize - 如何更新 n-m 关系中的关联,包括连接表
【发布时间】:2017-01-01 06:47:55
【问题描述】:

我有两个表(用户、标签),它们通过连接实体(user_tag)通过 belongsToMany 关系相互连接:

sequelize.define('tag', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    type: {
      type: DataTypes.STRING
    }
  }, {
       classMethods: {
            associate: function (models) {
            this.belongsToMany(models.user, {as: "users", through: models.user_tag });
  },
  }

}

sequelize.define('user', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING,
    },{
    classMethods: {
        associate: function (models) {
         this.belongsToMany(models.tag, { as:"tags", through: models.user_tags });
        }
    }
}


sequelize.define('user_tag', {
    type: DataTypes.STRING,
    param1: DataTypes.INTEGER,
    priority: DataTypes.INTEGER
  }, {
    freezeTableName: true,
    paranoid: true
  });

现在,用户可以更新他的所有标签,包括关于连接实体 (user_tag) 的所有特定信息,例如优先级和参数 1。

我知道 setAssociation [ 例如user.setTag(myTags) ] 但是,如何设置匹配的 param1 和 priority 属性?

【问题讨论】:

    标签: mysql sequelize.js


    【解决方案1】:

    根据Sequelize's documentation 添加与belongsToMany 的新关系时,您可以将附加属性传递给选项对象,该数据将被添加到直通模型中。

    user.setTag(myTags, { param1: 1, priority: 1 });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2019-10-05
      • 2014-11-08
      • 1970-01-01
      相关资源
      最近更新 更多