我正在使用 Sequelize 、 PostgreSQL 和 Node JS 。
我的数据库是这样设计的:
在关联表中,我为表 A、表 B 和表 C ID 添加了外键。
所以关联表看起来像这样:
| id | tableA_id | tableB_id | tableC_id |
表 A 关联:Table A => Has **Many** Table **B**.
Table A => Has **Many** Table **C**.
表 B 关联:Table B => Has **One** Table **A**.
Table B => Has **Many** Table **C**.
表 关联:Table C => Has **One** Table **A**.
Table C => Has **One** Table **B**.
话虽如此,我在 Sequelize 中有以下关联: TableAssociationModel.hasMany(TableAModel, {
as: 'TableAModel',
foreignKey: 'tableA_id',
targetKey: 'tableA_id',
});
TableAssociationModel.hasMany(TableBModel, {
as: 'TableBModel',
foreignKey: 'tableB_id',
targetKey: 'tableB_id',
});
TableAssociationModel.hasMany(TableCModel, {
as: 'TableCModel',
foreignKey: 'tableC_id',
targetKey: 'tableC_id',
});
数据库示例:| id | tableA_id | tableB_id | tableC_id |
| 1 | 2 | 1 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 2 | 2 | 3 |
如果我搜索 Table C ID = 1,我会得到我的关联,但如果我搜索 ID = 2,那么下面的表 A 或表 B 数据会通过。此外,我在我的表(A、B 和 C)中进行搜索,并希望在表关联中返回我的关联。
请问有什么帮助吗?
提前致谢,我希望我对自己的解释足够好,如有任何疑问,请告诉我,真的很想了解这是如何工作的。
PS:我是小学生,不要太苛刻xD
最佳答案
所以我想通了:
TableAModel.hasMany(TableAssociationModel, {
as: 'relationsData',
foreignKey: 'tableA_id',
sourceKey: 'tableA_id',
});
TableAssociationModel.belongsTo(TableAModel, {
as: 'tableAData',
foreignKey: 'tableA_id',
sourceKey: 'tableA_id',
});
TableBModel.hasMany(TableAssociationModel, {
as: 'relationsData',
foreignKey: 'tableB_id',
sourceKey: 'tableB_id',
});
TableAssociationModel.belongsTo(TableBModel, {
as: 'tableBData',
foreignKey: 'tableB_id',
sourceKey: 'tableB_id',
});
TableCModel.hasMany(TableAssociationModel, {
as: 'relationsData',
foreignKey: 'tableC_id',
sourceKey: 'tableC_id',
});
TableAssociationModel.belongsTo(TableCModel, {
as: 'tableCData',
foreignKey: 'tableC_id',
targetKey: 'tableC_id',
});
我的协会只有一种方式并且做错了。发现即使我想在 TableAssociationModel 中搜索,我的主要模型是表 A、B 和 C,所以我需要将它们视为更重要的,并告诉 Sequelize 它们是主要的。
顺便说一句,如果您想查看在 Sequelize 中生成的查询,您可以使用:
DEBUG=sequelize* node ***your/file.js***
your/file.js <= 你使用的文件,例如:TableAModel.findAll({
})
关于node.js - Sequelize Associations - 关联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63114269/