0

I use NestJj,PostgreSQL and Graphql for Back-End, Flutter,graphql_flutter for Front End.

I have a collection store like this :

enter image description here

I want to get the following result:

[
    {
        type:'A',
        details:[
            {name:'Food1'}    
        ]
    },
    {
        type:'Expense',
        details:[
            {name:'gym'},
            {name:'Dinner'}
        ]
    },
    {
        type:'Revenue',
        details:[
            {name:'Revenue'}    
        ]
    }
]

For show on the device : enter image description here How can I query? Could you help me?

Roeurb Navy
  • 71
  • 1
  • 9
  • If you are using PostgreSQL then why have you tagged SQL Server which is a totally different product? – Dale K Nov 16 '22 at 09:06
  • I removed it from my tags. – Roeurb Navy Nov 16 '22 at 09:16
  • So is this a flutter question, node.js question - or Postgresql question? Do you have data in postgres, and you are asking how to get it to flutter app? Or the data is already in flutter app and you need to reformat it as per your format? – Andrija Nov 16 '22 at 09:54
  • I use Back End (`nestjs with PostgresSql and graphql`) and Front End (`flutter with graphql_flutte`) – Roeurb Navy Nov 16 '22 at 09:59
  • Query the database to get the desired results and map them through the json return model The query result cannot be returned as json. – Dev Lởm Nov 16 '22 at 10:08

1 Answers1

0

I'm not sure if you'll be able to build that structure at the level of SQL. What you can do is to extract the data from the table wit the structure as it is and then map it at the level of JS.

// here's an example with TypeORM
const data = await Collection.findBy({...});
const result = data.map(item => ({
    type: item.type,
    details: [{
        name: item.name
    }]
}));

P.S. I'm pretty sure that's not the answer you've expected but it will solve your issue.

  • I added an image to expect to show on my device. Do you have another solution? – Roeurb Navy Nov 16 '22 at 15:30
  • Thanks for the screenshot. In order to group the items you can `reduce` the array, here's a good example of that: https://stackoverflow.com/a/34890276/7119067. Or you can use lodash's groupBy implementation: https://www.npmjs.com/package/lodash.groupby – Dinu Mihnea Nov 16 '22 at 16:11