【发布时间】:2020-07-29 17:03:40
【问题描述】:
我正在使用 Sequelize、PostgreSQL 和 Node JS。
我的数据库是这样设计的:
- 表 A => ID 自动递增
- 表 B => ID 自动递增
- 表 C => ID 自动递增
- 表关联 => ID 是自动递增的
在关联表中,我为表 A、表 B 和表 C 的 ID 添加外键。
所以 Association 表看起来像这样:
| 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**.
表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 |
如果我搜索表 C ID = 1,我会得到我的关联,但如果我搜索 ID = 2,则表 A 或表 B 数据都不会传递。
另外,我在我的表(A、B 和 C)中进行搜索,并希望在表关联中返回我的关联。
有什么帮助吗?
在此先感谢,我希望我对自己的解释足够好,如有任何疑问,请告诉我,真的很想了解这是如何工作的。
PS:我是小学生,不要太苛刻xD
【问题讨论】:
-
能否提供sequelize查询代码和生成的sql查询?
-
@Mansur 谢谢你的可用性,我已经纠正了这个问题,将在下面添加解决方案,以防有人遇到同样的问题。
标签: node.js database postgresql foreign-keys sequelize.js