简体   繁体   中英

Create an array in query Knex

So what I am trying to do is query for a list of items and group them based on their group Ids. I am new to mySQL, and I would like to know two things:

  1. How you would create a new property to store this array
  2. How would you grab these items in such a way that you can put them in said array

I am joining two tables together and it is resulting in something like the following:

{
  itemId1,
  itemId2,
  itemName,
  groupId,
  groupName
}

What I want to do is make it look like the following:

{
  groupName,
  groupId,
  itemArray:[{ itemId1, itemName }]
}

Is what I am doing even possible with just using knex alone?

Edit: I don't necessarily need a solution, but just some advice that would point me to the right direction.

I managed to figure out how to do it. For those who are may come across a similar problem, I found using JSON_ARRAYAGG, json_object and groupBy as good tools to use when creating the data structure that I was trying to query for. When using JSON_ARRAYAGG and json_object, you will need to use knex.raw because I don't think knex has those two functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM