knex: what is the appropriate way to create an array from results?

孤街醉人 提交于 2021-02-07 01:40:34

问题


I have an endpoint that joins the user and user_emails table as a one-to-many relationship (postgresql). It look as follows.

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

However, this will return a new document for each email address. What I want is an array of documents that looks as follows:

[{
  id: 1,
  name: 'Steve',
  emails: [
    { address: 'hello@world.org' },
    { address: 'meow@meow.org' }
  ]
}, {
  id: 2,
  name: 'Jimmy',
  emails: [
    { address: 'jimmy@jimbo.org' }
  ]
}]

How should this be done in knex?


回答1:


Assuming you're using Postgres - you need to use array_agg function to generate arrays. I would suggest using knex.raw

Please let me know if this works.

   knex('users')
    .innerJoin('user_emails','users.id','user_emails.user_id')
    .select([
      'users.id as userID',
      'users.name as userName',
      knex.raw('ARRAY_AGG(user_emails.adress) as email')
    ])
    .groupBy('users.id','users.name')


来源:https://stackoverflow.com/questions/37255577/knex-what-is-the-appropriate-way-to-create-an-array-from-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!