我使用了 Sequelize 并使用 belongsToMany()
设置了多对多关系。但是,当我查询出数据时,像这样:
api.models.operator.find({
where: { id: connection.params.id },
include: [
{ model: api.models.permission,
include: [
{ model: api.models.activity }
]
}
]
})
我收到一个 activity is not associated to permission!
错误。为什么? belongsToMany 通过 Permission 将 Activity 连接到 Operator 是否意味着关联?
我的权限模型:
module.exports = function(sequelize, DataTypes) {
return sequelize.define("permission",
{
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
operator_id: {
type: DataTypes.BIGINT,
allowNull: false,
references: 'operator',
referencesKey: 'id',
comment: "The Operator in this Permission."
},
activity_id: {
type: DataTypes.BIGINT,
allowNull: false,
references: 'activity',
referencesKey: 'id',
comment: "The Activity in this Permission."
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
comment: "Date of record creation."
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
comment: "Date of last record update."
},
deletedAt: {
type: DataTypes.DATE,
comment: "Date record was marked as deleted."
}
},
{
comment: "A Permission indicates an allowed Activity by an Operator, ex: superadmin is allowed to 'POST /workorders'.",
classMethods: {
associate: function(models) {
models.operator.belongsToMany(models.activity, {through: models.permission, foreignKey: 'operator_id', onDelete: 'CASCADE', onUpdate: 'CASCADE'});
models.activity.belongsToMany(models.operator, {through: models.permission, foreignKey: 'activity_id', onDelete: 'CASCADE', onUpdate: 'CASCADE'});
}
}
}
);
}
最佳答案
我自己解决如下:
ModelA.belongsToMany(ModelB, {
through: 'ModelC',
foreignKey: 'ModelAID'
});
你只调用:
ModelA.findAll({
include: [{
model: ModelB
}]}).then(function(success) {}, function(error) {});
如果你想使用:
ModelB.findAll({
include: [{
model: ModelA
}]}).then(function(success) {}, function(error) {});
你必须声明
ModelB.belongsToMany(ModelA, {
through: 'ModelC',
foreignKey: 'ModelBID'
});
^^ 祝你好运!!!! ^^.
关于many-to-many - Sequelize belongsToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29547686/