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

How to match column value of boolean in Typeorm QueryBuilder?

1个答案

1

When using TypeORM's QueryBuilder to match boolean column values, it can be achieved through straightforward comparison operations. Here's a concrete example:

Suppose we have an entity named User with a boolean column isActive. Now, we want to query all active users (i.e., users where isActive is true).

First, ensure that your TypeORM environment is set up and necessary classes and entities are imported. Here is an example code snippet using QueryBuilder to query active users:

typescript
import { getRepository } from "typeorm"; import { User } from "./entity/User"; async function getActiveUsers() { const userRepository = getRepository(User); const activeUsers = await userRepository .createQueryBuilder("user") .where("user.isActive = :isActive", { isActive: true }) .getMany(); return activeUsers; }

In this example:

  • "user" is an alias for the query subject.
  • .where("user.isActive = :isActive", { isActive: true }) sets the query condition, where :isActive is a parameter whose value is passed via the second parameter object { isActive: true }, indicating that we only want users where isActive is true.
  • .getMany() indicates that we expect to return multiple matching records.

This approach is straightforward and easy to understand. You can adjust the query conditions based on your specific requirements to match different boolean values or other column types.

2024年6月29日 12:07 回复

你的答案