我已经通过名称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/