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

后端 未结 1 1730
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-14 21:17

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         


        
1条回答
  •  渐次进展
    2021-02-14 21:52

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

    0 讨论(0)
提交回复
热议问题