从各种Sails.js模型关联中获取扁平JSON
我有这样的层次结构:从各种Sails.js模型关联中获取扁平JSON,sails.js,waterline,Sails.js,Waterline,我有这样的层次结构:PersonTeamDepartment 我想从这样一个人身上提取扁平化记录: { "name": "Foo", "id": 1, ... "team": { "name": "MGMT", "id": 1, "department": 1 ... }, "department": { "name": "Top", "id": 1, "office": 1 ... } } 这些是模
PersonTeamDepartment
我想从这样一个人身上提取扁平化记录:
{
"name": "Foo",
"id": 1,
...
"team": {
"name": "MGMT",
"id": 1,
"department": 1
...
},
"department": {
"name": "Top",
"id": 1,
"office": 1
...
}
}
这些是模型:
人
// A person that belongs to a team
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
//Assosiations
team: {
model: 'team'
},
department: {
model: 'department',
via: 'team.department'
},
}
};
团队
系
// A department that has many teams
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
teams: {
collection: 'team',
via: 'department'
}
}
};
我不能这样做(是的,它有更多的级别):
有没有更好的方法?如果您使用Mongo,您可以使用Promissions。看起来好多了
var composeRecord
Person.findById(1).then(function(people){
composeRecord = people[0]
return Team.findById(people[0].team)
}).then(function (teams) {
composeRecord.team = teams[0]
return Department.findById(teams[0].department)
}).then(function(departments){
composeRecord.department = departments[0]
return Office.findById(departments[0].office)
}).then(function(offices){
composeRecord.office = offices[0]
return Company.findById(offices[0].company)
}).then(function(companies){
composeRecord.company = companies[0]
res.json(composeRecord)
}).catch(function (err) {
console.log(err)
})
如果您使用的是MySQL o PG之类的关系数据库,那么您应该编写一个数据库查询并使用@FilipeMoraisJorge。它可以工作,但如果您使用连接编写查询,它会工作得更快。因此,我选择对数据库不可知还是执行得更快。再次感谢。你也可以试试。Id支持深度填充。如果你有合适的密钥,你的代码就会更像这个人。findById(1)。填充('team')。填充('department')。填充('office')。填充('company')。然后()
function (req, res) {
Person.findById(1).exec(function (err, people) {
Team.findById(people[0].team).exec(function (err, teams) {
Department.findById(teams[0].department).exec(function (err, departments) {
Office.findById(departments[0].office).exec(function (err, offices) {
Company.findById(offices[0].company).exec(function (err, companies) {
var composeRecord = Object.assign(
people[0], {
team: teams[0],
department: departments[0],
office: offices[0],
company: companies[0],
});
res.send(composeRecord);
})
})
})
})
})
}
var composeRecord
Person.findById(1).then(function(people){
composeRecord = people[0]
return Team.findById(people[0].team)
}).then(function (teams) {
composeRecord.team = teams[0]
return Department.findById(teams[0].department)
}).then(function(departments){
composeRecord.department = departments[0]
return Office.findById(departments[0].office)
}).then(function(offices){
composeRecord.office = offices[0]
return Company.findById(offices[0].company)
}).then(function(companies){
composeRecord.company = companies[0]
res.json(composeRecord)
}).catch(function (err) {
console.log(err)
})