unable to select alias in getMany Typeorm
Asked Answered
D

3

0

I'm using TypeORM(mySQL) for my Nestjs App. I want to change the column name on select using querybuilder. but it's not working.

const order = await this.connection
        .createQueryBuilder(Orders,"order")
        .where("customer_id = :userId", { userId })
        .select(["order.id","order.hashed_id AS hash","order.paid AS payment"])
        .getMany();

same applies on leftjoin and addSelect

.leftJoin("variety.product","product")
.addSelect([`product.name_${language} AS name`,"product.image_url"])

How Can we set Alia's in TypeORM

Disjointed answered 7/7, 2022 at 16:35 Comment(0)
C
1

I was also struggling with this. Apparently you have to use getRawMany() instead of getMany() because the return data is not an entity. Found this out here https://github.com/typeorm/typeorm/issues/9114

Coccidiosis answered 11/10, 2023 at 13:32 Comment(0)
W
0

When using TypeORM's QueryBuilder, you can use aliases for selected columns. These aliases can be useful for computed columns or for renaming columns in the result set. However, the aliases themselves are not included in the final result.

Here's an example of using aliases with getMany():

const orders = await this.connection
    .createQueryBuilder(Orders, "order")
    .where("customer_id = :userId", { userId })
    .select(["order.id"])
    .addSelect(`order.paid`, 'payment')
    .addSelect(`order.hashed_id`, 'hash')
    .getMany();

In this example, payment and hash are aliases for the order.paid and order.hashed_id columns, respectively. These aliases are used in the query but are not included in the result set.

If you need to use aliases and include them in the result set, you can use getRawMany():

const orders = await this.connection
    .createQueryBuilder(Orders, "order")
    .where("customer_id = :userId", { userId })
    .select([
        "order.id",
        "order.hashed_id AS hash",
        "order.paid AS payment"
    ])
    .getRawMany();

In this example, the aliases hash and payment are used to rename the order.hashed_id and order.paid columns, respectively. These aliases will be included in the result set.

Remember, when using aliases with getRawMany(), the result set will be an array of objects with the aliased column names as keys.

Wivinia answered 13/5 at 8:54 Comment(0)
D
-1

Just remove "[]". addSelect have two overlap:

  • addSelect(queryStrs: string[])

  • addSelect(queryStr: string, alias: string)

    .addSelect(`product.name_${language} AS name`,"product.image_url")
    
Dedradedric answered 8/7, 2022 at 4:58 Comment(1)
@Tran that's the wrong syntax. I want to use n columns which is not possible with this.Disjointed

© 2022 - 2024 — McMap. All rights reserved.