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'
}]
}]
}]