我有三个基本表A,B和C。A和B具有多对多关系。因此,我使用A_B的联结表。 C与A_B具有一对多关系。这就是使用续集时的定义方式。
A.associate = function(models) {
A.belongsToMany(models.B, {
through: 'A_B',
as: 'Bs',
foreignKey: 'a_id'
});
};
B是相似的,然后是C。
C.associate = function(models) {
C.hasMany(models.A_B, {
as: 'ABs',
foreignKey: 'c_id'
});
};
但是当我运行它时,我收到以下消息。
Error: C.hasMany called with something that's not a subclass of Sequelize.Model
似乎sequelize无法识别A_B为有效。有什么办法解决吗?
谢谢。
答案 0 :(得分:0)
如果要获取A_B表中的行,则需要创建一个表示它的模型(当您在A中通过through声明关联时,不会在序列化中“创建”该模型)。
假设:
代码应类似于:
const A = sequelize.define('A', {
id: Sequelize.STRING
})
A.associate = function(models) {
A.belongsToMany(models.B, {
through: {
model: 'A_B',
},
as: 'Bs',
foreignKey: 'a_id',
otherKey: 'b_id'
});
}
const B = sequelize.define('B', {
id: Sequelize.STRING
})
B.associate = function(models) {
B.belongsToMany(models.A, {
through: {
model: 'A_B',
},
as: 'As',
foreignKey: 'b_id',
otherKey: 'a_id'
});
}
const A_B = sequelize.define('A_B', {
a_id: Sequelize.STRING,
b_id: Sequelize.STRING,
c_id: Sequelize.STRING
})
const C = sequelize.define('C', {
id: Sequelize.STRING
})
C.associate = function(models) {
C.hasMany(models.A_B, {
as: 'ABs',
foreignKey: 'c_id'
});
}