我有一个端点连接user
and user_emails
表作为一对多关系(postgresql)。它看起来如下。
router.get('/', function (req, res, next) {
db.select('users.id', 'users.name', 'user_emails.address')
.from('users')
.leftJoin('user_emails', 'users.id', 'user_emails.user_id')
.then(users => res.status(200).json(users))
.catch(next) // go to error handler
});
但是,这将为每个电子邮件地址返回一个新文档。我想要的是一组如下所示的文档:
[{
id: 1,
name: 'Steve',
emails: [
{ address: '[email protected] /cdn-cgi/l/email-protection' },
{ address: '[email protected] /cdn-cgi/l/email-protection' }
]
}, {
id: 2,
name: 'Jimmy',
emails: [
{ address: '[email protected] /cdn-cgi/l/email-protection' }
]
}]
这应该如何在 knex 中完成?