gpt4 book ai didi

node.js - 使用 pg-promise 进行嵌套查询对象映射

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:09 24 4
gpt4 key购买 nike

我正在查看 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 实体与例如具有一对多关系。 汽车,我想列出连接到每个事件的所有汽车,我该如何使用map当我想要的对象深度超过一层时函数?

我想要的结果可能是这样的:

[{
//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
});

方法map简化了将检索到的行映射到其他内容的过程,并且由于我们将它们映射到 promise 中,因此需要解决这些问题,为此我们使用方法 batch 。我们对汽车的每个内部请求数组执行此操作,然后在顶层 - 解决事件的请求数组。

更新

如果将树逻辑颠倒过来,可能会更容易阅读和维护:

function getUsers(t) {
const getCars = eventId => t.any('SELECT * FROM Cars WHERE eventId = $1', eventId);

const getEvents = userId => t.map('SELECT * FROM Events WHERE userId = $1', userId, event => {
return getCars(event.id)
.then(cars => {
event.cars = cars;
return event;
});
}).then(t.batch);

return t.map('SELECT * FROM Users WHERE status = $1', ['active'], user => {
return getEvents(user.id)
.then(events => {
user.events = events;
return user;
});
}).then(t.batch);
}
<小时/>

还有一种更快的单查询方法,可以在这里找到:

关于node.js - 使用 pg-promise 进行嵌套查询对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com