In TypeORM, using QueryBuilder to select specific columns is a highly flexible approach that enables precise control over query output. Here, I will demonstrate how to use QueryBuilder to select specific columns with a concrete example.
Assume we have an entity named User with the following properties: id, firstName, lastName, email, and age.
To query all users while retrieving only the firstName and email columns, we can use QueryBuilder as follows:
typescriptimport { getRepository } from "typeorm"; async function getUsers() { const userRepository = getRepository(User); const users = await userRepository.createQueryBuilder("user") .select(["user.firstName", "user.email"]) .getMany(); return users; }
-
Creating QueryBuilder: First, we instantiate a QueryBuilder for the
Userentity by callinggetRepository(User).createQueryBuilder("user"). Here, "user" serves as the alias assigned to the entity, which will be referenced in subsequent queries. -
Selecting Specific Columns: Use the
.select(["user.firstName", "user.email"])method to specify the columns of interest. The arguments passed toselectare an array of column names formatted as "entityAlias.columnName". -
Executing the Query: Finally, invoke the
.getMany()method to execute the query and retrieve results. This returns an array of users containing only the selected columns.
This approach is particularly valuable when limiting returned columns is necessary, such as to minimize network data transmission or when certain data should remain hidden from clients. QueryBuilder allows you to construct and execute queries flexibly without compromising readability or control.