我使用了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是否通过权限将操作符连接到运算符意味着关联?
我的权限模型:
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'});
}
}
}
);
}
答案 0 :(得分:4)
我自己解决的问题如下:
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'
});
^^祝你好运!!!! ^^
答案 1 :(得分:0)
通过模型不直接与任何模型相关联。为了能够包含直通模型,您需要permissions.belongsTo(activity)
或类似的
答案 2 :(得分:0)
这个怎么样?我记得关系表数据将默认包装在连接表数据对象中。
api.models.operator.find({
where: { id: connection.params.id },
include: [
{
model: api.models.activity
}
]
})