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

How can I have IS NULL condition in TypeORM find options?

1个答案

1

In TypeORM, if you want to specify the IS NULL condition, you can use QueryBuilder or simply pass the condition in the find method. Here are examples of both methods:

Using the find Method

Assume you have an entity named User, and you want to find users where the lastLogin field is NULL. You can do this:

typescript
import { getRepository } from 'typeorm'; import { User } from './entity/User'; async function findUsersWithNoLastLogin() { const userRepository = getRepository(User); const users = await userRepository.find({ where: { lastLogin: IsNull(), }, }); return users; }

Here, IsNull() is a method provided by TypeORM to indicate that the field value should be NULL.

Using QueryBuilder

If you prefer using the more flexible QueryBuilder for queries, you can do this:

typescript
import { getRepository } from 'typeorm'; import { User } from './entity/User'; async function findUsersWithNoLastLoginQueryBuilder() { const userRepository = getRepository(User); const users = await userRepository .createQueryBuilder("user") .where("user.lastLogin IS NULL") .getMany(); return users; }

In this example, the createQueryBuilder method creates a new query builder instance to construct the SQL query. The where method accepts a string condition, here specifying lastLogin IS NULL.

In practical applications, the choice of method depends on your specific requirements. The find method is simple and straightforward, suitable for quick queries. Meanwhile, QueryBuilder provides greater flexibility and control, ideal for complex query scenarios.

2024年6月29日 12:07 回复

你的答案