使用pg-promise嵌套查询对象映射
我正在通过pg-promise的一个例子来说明方法映射 :
// 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
,当我想要的对象超过一个深度时,如何使用地图function?
我想要的结果可能看起来像这样:
[{ //This is a user id: 2, first_name: "John", last_name: "Doe", events: [{ id: 4, type: 'type', cars: [{ id: 4, brand: 'bmw' }] }] }]
我是pg-promise的作者。
function getUsers(t) { return t.map('SELECT * FROM Users WHERE status = $1', ['active'], user => { return t.map('SELECT * FROM Events WHERE userId = $1', user.id, event=> { return t.any('SELECT * FROM Cars WHERE eventId = $1', event.id) .then(cars=> { event.cars = cars; return event; }); }) .then(t.batch) // settles array of requests for Cars (for each event) .then(events=> { user.events = events; return user; }); }).then(t.batch); // settles array of requests for Events (for each user) }
然后使用它:
db.task(getUsers) .then(users => { // users = an object tree of users->events->cars }) .catch(error => { // error });
方法映射简化了将检索到的行映射到其他东西,并且由于我们将它们映射到承诺,需要解决,我们使用方法批处理 。 我们为每个内部的cars
请求数组,然后在最高层 – 解决events
请求数组。
还有一个更快的单一查询方法,可以在这里find:
- 使用PostgreSQL / NodeJS将JOIN表作为结果数组