Я имею эту иерархическую структуру: Person < has a > Team < has a > Department
Получить Свести JSON из различных Sails.js моделей ассоциаций
, и я хочу, чтобы извлечь расплющить запись от человека, как это:
{
"name": "Foo",
"id": 1,
...
"team": {
"name": "MGMT",
"id": 1,
"department": 1
...
},
"department": {
"name": "Top",
"id": 1,
"office": 1
...
}
}
Они являются модели:
PERSON
// 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 team with many persons and belongs to one department
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
//Associations
department: {
model: 'department'
},
members: {
collection: 'person',
via: 'team'
}
}
};
ОТДЕЛ
// A department that has many teams
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
teams: {
collection: 'team',
via: 'department'
}
}
};
Я не могу это сделать, как это (да, он имеет больше уровней):
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);
})
})
})
})
})
}
Любые идеи, как сделать это лучше?
Напишите запрос к базе данных и использовать [ '.query'] (http://sailsjs.com/documentation/reference/waterline-orm/models/query) – Sangharsh