简体   繁体   中英

How to group array data returned based from entity column value - TypeORM / Postgres in NestJS

I have following 2 tables with following values:

course_tbl

id title
1 course_1
2 course_2

modules_table

id title is_finished course_id
1 module_1 true 1
2 module_2 true 1
3 module_3 false 1
4 module_4 true 2
5 module_5 false 2

Basically, the format or the return I am looking for is something like this:

[
    {
        id: 1
        title: course_1
        finishedModules: [ 
            {
                id: 1
                title: module_1
            }, 
            {
                id: 2
                title: module_2
            }
        ],
        unfinishedModules: [ 
            {
                id: 3
                title: module_3
            }
        ]
    },
    {
        id: 2
        title: course_2
        finishedModules: [ 
            {
                id: 4
                title: module_4
            }
        ],
        unfinishedModules: [ 
            {
                id: 5
                title: module_5
            }
        ]
    }
]

I tried doing, this.courseRepository.find({ relations: ['modules'] }) , but it only does the basic left join query.

There's a transformer option @Column decorator which could group data in desired format: https://orkhan.gitbook.io/typeorm/docs/entities#column-options

In your CourseEntity you could do this

@Column({ 
  transformer: {
    to: (value: DatabaseType) => <if is_finished true return object, otherwise do nothing>,
    from: (value: DatabaseType) => value
  }
})
finishedModules: Module

@Column({ 
  transformer: {
    to: (value: DatabaseType) => <if is_finished false return object, otherwise do nothing>,
    from: (value: DatabaseType) => value
  }
})
unfinishedModules: Module

In theory, transformer function should be triggered on find, and DatabaseType should contain query results, but I'm not sure how DatabaseType looks like in reality, since it's undocumented.

But, this is quite inefficient method, maybe it would be easier to add some reducer on find query result with finishedModules and unfinishedModules as a reducer response.

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