0

For example say you have a user that can have many products and a product could have one brand, your rows come back from MySQL in a json object similar to this

[
  {
    id: 1,
    name: "robert",
    productID: 150,
    productName: "apple",
    brandID: 3,
    brandName: 'sonoma'
  },
  {
    id: 1,
    name: "robert",
    productID: 22,
    productName: "ice",
    brandID: 3,
    brandName: 'sonoma'
  },
  {
    id: 2,
    name: "willy",
    productID: 150,
    productName: "apple",
    brandID: 3,
    brandName: 'sonoma'
  }
]

but you want it to look like:

    [
      {
        id: 1,
        name: "robert",
        Products: [
          {
            productID: 150,
            productName: "apple",
            Brand: {
              brandID: 3,
              brandName: 'sonoma'
            }
          },
          {
            productID: 22,
            productName: "ice",
            Brand: {
              brandID: 3,
              brandName: 'sonoma'
            }
          }
        ]
      },
      {
        id: 2,
        name: "willy",
        Products: {
          productID: 150,


    productName: "apple",
      Brand: {
        brandID: 3,
        brandName: 'sonoma'
      }
    }
  }
]

Are there any tools you can use to automatically format things in this manner? Or should I just do it myself with a .map. It seems like this would have had to be done many times before, and i'm sure theres a good way to do it.

Thank you!

edit im not asking how to do this inside of a language like php, I'm asking how to do it in raw SQL.

Sammy Roberts
  • 657
  • 1
  • 7
  • 15

0 Answers0