【发布时间】:2019-02-21 10:59:06
【问题描述】:
我正在尝试合并一些嵌套的 JSON 数组而不查看 id。目前,当我向/surveyresponses 发出GET 请求时,我得到了这个:
{
"surveys": [
{
"id": 1,
"name": "survey 1",
"isGuest": true,
"house_id": 1
},
{
"id": 2,
"name": "survey 2",
"isGuest": false,
"house_id": 1
},
{
"id": 3,
"name": "survey 3",
"isGuest": true,
"house_id": 2
}
],
"responses": [
{
"question": "what is this anyways?",
"answer": "test 1"
},
{
"question": "why?",
"answer": "test 2"
},
{
"question": "testy?",
"answer": "test 3"
}
]
}
但我想在每个调查都有自己的问题和答案的地方得到它,所以像这样:
{
"surveys": [
{
"id": 1,
"name": "survey 1",
"isGuest": true,
"house_id": 1
"question": "what is this anyways?",
"answer": "test 1"
}
]
}
因为我不会去特定的id,所以我不确定如何让这种关系发挥作用。这是产生这些结果的当前查询。
export function getSurveyResponse(id: number): QueryBuilder {
return db('surveys')
.join('questions', 'questions.survey_id', '=', 'surveys.id')
.join('questionAnswers', 'questionAnswers.question_id', '=', 'questions.id')
.select('surveys.name', 'questions.question', 'questions.question', 'questionAnswers.answer')
.where({ survey_id: id, question_id: id })
}
【问题讨论】:
-
请先声明您的 Postgres 版本和表定义。
json或jsonb? -
我冒昧地修正了术语和语法以使问题保持一致。我做对了吗?
标签: sql node.js postgresql express