【发布时间】:2016-07-13 20:04:49
【问题描述】:
我在下面的代码中使用“nestTables”选项将从 SQL 查询返回的数据分离到各自的表中。我还在查询中包含了一个计算字段,我想将其包含在主表中。
例如,我正在执行以下路线:
router.route('/person/:personId').get(function(req,res){
var person_id = req.params.personId;
db.getConnection(function(err, connection) {
if (err) {
return res.status(503).send({ result: false, error: 'CONNECTION error: ' + err.code});
} else {
var sqlString='SELECT *, someField - 1 as calculated FROM person LEFT JOIN person_status ON person.id = person_status.person_id WHERE person.id = ' + person_id;
var options={sql:sqlString,nestTables:true};
connection.query(options, function(error, rows, fields) {
connection.release();
var nestingOptions = [
{tableName: 'person', pkey:'id'},
{tableName: 'person_status', pkey:'id', fkeys:[{table:'person',col:'person_id'}]}
];
if (error) {
return res.status(500).send({ result: false, error: 'QUERY ERROR: ' + error.code});
} else {
return res.status(200).send(rows);
}
});
}
});
});
我收到以下 JSON 响应:
[
{
"person": {
"id": 1,
other person data . . .
"person_status": [
{
"id": 3,
other data . . .
}
]
},
"person_status": {
"id": 3,
other data . . .
},
"": {
"calculated": 0
}
}
]
理想情况下,我想将计算字段包含到人员子组中,如下所示:
[
{
"person": {
"id": 1,
"calculated": 0
other person data . . .
"person_status": [
{
"id": 3,
other data . . .
}
]
},
"person_status": {
"id": 3,
other data . . .
}
}
]
有什么方法可以将计算字段包含到 person 表中,还是有更好的解决方案来解决这个问题?
提前致谢!
【问题讨论】:
标签: json node.js node-mysql