1
我会通过一个实例从pg-promise的方法map:嵌套查询对象的映射
// Build a list of active users, each with the list of user events:
db.task(t => {
return t.map('SELECT id FROM Users WHERE status = $1', ['active'], user => {
return t.any('SELECT * FROM Events WHERE userId = $1', user.id)
.then(events=> {
user.events = events;
return user;
});
}).then(t.batch);
})
.then(data => {
// success
})
.catch(error => {
// error
});
比方说,Event
实体有一个与许多例如关系Cars
,我想列出连接到每个event
的所有cars
,当我想要的对象的深度超过一个级别时,如何使用map函数?
结果我想可能是这个样子:
[{
//This is a user
id: 2,
first_name: "John",
last_name: "Doe",
events: [{
id: 4,
type: 'type',
cars: [{
id: 4,
brand: 'bmw'
}]
}]
}]