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实体与 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'
        }]
    }]
}]
4

1 回答 1

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)
}

然后使用它:

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

方法map简化了将检索到的行映射到其他内容,并且由于我们将它们映射到 promise,因此需要解决这些问题,为此我们使用方法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);
}

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

于 2016-10-27T00:45:21.803 回答