乐闻世界logo
搜索文章和话题

How to remove prefix from returned columns in typeorm querybuilder

1个答案

1

In TypeORM's QueryBuilder, to remove prefixes from returned columns in your query results, you can specify column names in the select method and use aliases to eliminate the prefixes. Here is an example of removing prefixes from returned columns using QueryBuilder:

Suppose we have an entity named User with two fields, id and name. We typically query it as follows:

typescript
const users = await connection .getRepository(User) .createQueryBuilder("user") .select(["user.id", "user.name"]) .getMany();

This will return results similar to the following, where columns have the user prefix:

json
[ { "user.id": 1, "user.name": "John Doe" }, { "user.id": 2, "user.name": "Jane Doe" } ]

To remove these prefixes, specify aliases for the fields in the select method without using the table alias. This prevents the table alias from appearing as a prefix in the returned results. For example:

typescript
const users = await connection .getRepository(User) .createQueryBuilder("user") .select("user.id", "id") .addSelect("user.name", "name") .getMany();

After executing the above query, you will get results without the user prefix:

json
[ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Doe" } ]

In this example, by assigning aliases to each selected field without prefixes, we successfully remove the column prefixes from the query results.

2024年6月29日 12:07 回复

你的答案