【发布时间】:2018-03-16 16:26:11
【问题描述】:
我想使用 SequelizeJS 递归地从 Postgres 数据库中获取包括所有关联模型的数据。
地理位置表
id | isoCode | name | parentId | type | updatedAt | deletedAt
parentId 持有父 GeoLocation 的 id。
模型关联
GeoLocation.belongsTo(GeoLocation, {
foreignKey: 'parentId',
as: 'GeoLocation'
});
数据说明及示例
GeoLocation 类型及其关系:
city -> subdivision -> country -> continent
id: 552, name: Brooklyn, type: city, parentId: 551
id: 551, name: New York, type: subdivision, parentId: 28
id: 28, name: United States, type: country, parentId: 27
id: 27, name: North America, type: continent, parentId: NULL
现在,当查询一个城市时,只要设置了parentId,我希望包含所有关系。
GeoLocation.findOne({
where: {
id: 552
},
include: [
{
model: GeoLocation,
as: 'GeoLocation',
include: [
{
model: GeoLocation,
as: 'GeoLocation',
include: [
{
model: GeoLocation,
as: 'GeoLocation',
}
],
}
],
}
],
});
JSON 响应
{
"GeoLocation":{
"id":552,
"type":"city",
"name":"Brooklyn",
"GeoLocation":{
"id":551,
"type":"subdivision",
"name":"New York",
"GeoLocation":{
"id":28,
"type":"country",
"name":"United States",
"GeoLocation":{
"id":27,
"type":"continent",
"name":"North America"
}
}
}
}
}
上述解决方案有效,但我有强烈的感觉,有更好的方法来做到这一点,而不必多次包含模型。我在文档中找不到任何相关内容。我错过了什么吗?
【问题讨论】:
-
我正在寻找相同的东西,以及 MariaDB :) 如果您碰巧克服了这个问题,请分享您的解决方案 ^^
-
@Deunz Nah,我一直坚持到项目结束。但我仍然希望看到比这更好的解决方案 :)
标签: postgresql recursion sequelize.js