sequelize.js - 如何通过 sequelize 中的 setAssociation 选项在连接表中设置参数?

标签 sequelize.js polymorphic-associations jointable

我已经通过名称labels_association 定义了表的模式,它将标签和模型X 关联如下:

'use strict';

module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.createTable('labels_association', {
      labelId: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      associationId: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      associationType: {
        allowNull: false,
        type: Sequelize.ENUM('x', 'y')
      }
    });
  },
  down: function(queryInterface) {
    return queryInterface.dropTable('labels_association');
  }
};

通过labels_association表定义具有和属于模型X与标签的许多关系
X.belongsToMany(Label, {
  as: 'labels',
  through: {
    model: 'labels_association',
    attributes: ['associationId', 'associationType'],
    scope: {
      associationType: 'x'
    }
  },
  foreignKey: 'associationId',
  otherKey: 'labelId'
});

尽管在为模型 X 的实例设置标签时,我无法将关联类型设置为“x”,而它应该已经由belongsToMany 关联中的范围属性处理。
instanceOfX.setLabels(labelIds, {
  associationType: 'x'
})

在上述情况下,如何设置值为 'x' 的 associationType?

最佳答案

引用 Github 上跟踪的这个问题 https://github.com/sequelize/sequelize/issues/5378

需要为关系表创建模型如下:

let LabelAssociation = sequelize.define('labelAssociation', {
  associationType: {
    type: STRING
    // etc
  }
}, {
  tableName: 'label_associations'
});

X.belongsToMany(Label, {
  as: 'labels',
  through: {
    model: LabelAssociation,
    attributes: ['associationId', 'associationType'],
    scope: {
      associationType: 'x'
    }
  },
  foreignKey: 'associationId',
  otherKey: 'labelId'
});

解释如下:

The string argument(through.model in belongsToMany options) is specifically to define a table name for an autogenerated model. If you haven't defined a model for the join model, you need to yes, otherwise Sequelize doesnt know that these extra attributes exist.

关于sequelize.js - 如何通过 sequelize 中的 setAssociation 选项在连接表中设置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35264797/

相关文章:

javascript - 我怎样才能绑定(bind)一个变量来 Sequelize 文字?

mysql - 在 '' 中 Sequelize 未知列 'on clause'

node.js - 锁定 postgres 事务

sql - 使用 NodeJS 应用程序的 Sequelize 函数在 PostgreSQL 中实现两级聚合

ruby-on-rails - ActiveRecord、has_many :through, 和多态关联

ruby-on-rails-3 - 无法批量分配 protected 属性 : address

java - ActiveJDBC 多态父级的热切加载

mysql - 根据外部 csv 文件的内容更新现有的 sql 表?

node.js - Sequelize - 使用 AND 运算符连接查询表

hibernate ,将表与附加列连接起来