'TypeORM - orderBy with value

I have a problem with ordering records by value from my SomeEnum, here is my code

export enum SomeEnum{
    IMPORTANT = 'Important',
    NICE_TO_READ = 'Nice to read',
    OPINION = 'Opinion'
}

@Entity()
export class SomeEntity extends GenericEntity {

    //some columns 

    @Column({
        nullable: true
    })
    label: SomeEnum;
}
const wiki = await this.conn.getRepository(SomeEntity).createQueryBuilder('some')
            .where('some.id = :id', { id: someId})
            .orderBy() //HERE

I want to sort my data, so that all records containing the value Important from SomeEnum are at the top ot my response, how to do this?

thanks for any help!

//////////////////////////////////////////////////



Solution 1:[1]

You can use case in orderby, something like :

const wiki = await this.conn.getRepository(SomeEntity).createQueryBuilder('some')
            .where('some.id = :id', { id: someId})
            .orderBy(`(CASE WHEN some.label  IS ${SomeEnum.IMPORTANT} THEN 1 ELSE some.label END)`)

Solution 2:[2]

const wiki = await this.conn.getRepository(SomeEntity).createQueryBuilder('some')
            .where('some.id = :id', { id: someId})
            .orderBy(`(CASE WHEN some.label  IS ${SomeEnum.IMPORTANT} THEN 1 ELSE some.label END)`)
            .getRawMany();

use it with getRawMany() or getRawAndEntities();

sometimes you need to select some specific data,This data is not an entity, it's called raw data. To get raw data, you use getRawOne and getRawMany

See the documentation on QueryBuilder here for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Youba
Solution 2 Ammar Iqbal