使用pg-promise的嵌套查询对象映射

jus*_*ing 1 node.js 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
    });
Run Code Online (Sandbox Code Playgroud)

假设该Event实体与,例如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'
        }]
    }]
}]
Run Code Online (Sandbox Code Playgroud)

vit*_*y-t 5

我是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)
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

db.task(getUsers)
    .then(users => {
        // users = an object tree of users->events->cars
    })
    .catch(error => {
        // error
    });
Run Code Online (Sandbox Code Playgroud)

方法映射简化了将检索到的行映射到其他对象的过程,并且由于我们将它们映射到承诺中,因此需要解决这些问题,为此我们使用方法batch。我们先对每个内部请求数组进行处理cars,然后在顶层进行处理,以解决对的请求数组events

更新

如果您颠倒地执行树逻辑,则可能更易于阅读和维护:

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);
}
Run Code Online (Sandbox Code Playgroud)

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