我正在通过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
实体与 eg 具有一对多关系Cars
,并且我想列出所有cars
连接到每个的实体,当我想要的对象超过一层深度时event
,如何使用map函数?
我想要的结果可能是这样的:
[{
//This is a user
id: 2,
first_name: "John",
last_name: "Doe",
events: [{
id: 4,
type: 'type',
cars: [{
id: 4,
brand: 'bmw'
}]
}]
}]