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

How to properly use IsNotNull/ IsNull in Typeorm?

4 个月前提问
3 个月前修改
浏览次数67

1个答案

1

在 TypeORM 中,IsNotNullIsNull 是用于构建 SQL 查询的函数,特别是在查询中处理列的 NULL 值时非常有用。这两个函数可以帮助我们过滤出数据库中列值为 NULL 或非 NULL 的记录。

使用 IsNull

当你需要找出某个特定列值为 NULL 的所有记录时,可以使用 IsNull 函数。例如,假设我们有一个名为 User 的实体,其中包含一个可能为 NULL 的 lastLoginDate 字段。如果我们想找到所有从未登录过的用户(即 lastLoginDate 字段为 NULL 的用户),我们可以这样写:

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

使用 IsNotNull

相反地,当你需要找出某个特定列值不为 NULL 的所有记录时,可以使用 IsNotNull 函数。还是以 User 实体为例,如果我们想找到所有至少登录过一次的用户(即 lastLoginDate 字段不为 NULL 的用户),我们可以这样写:

typescript
import { getRepository, IsNotNull } from "typeorm"; import { User } from "./entity/User"; async function findUsersLoggedIn() { const userRepository = getRepository(User); const users = await userRepository.find({ where: { lastLoginDate: IsNotNull() } }); return users; }

总结

使用 IsNullIsNotNull 可以非常方便地处理数据库中的 NULL 值问题,它们是 TypeORM 提供的简洁的方法来构建涉及 NULL 值逻辑的查询。通过示例可以看到,这两个函数在实际应用中可以帮助开发者简化代码并直观地处理数据筛选的需求。这些函数在处理数据完整性和可选字段时尤其有用,可以帮助开发者写出更清晰、更可维护的代码。

2024年6月29日 12:07 回复

你的答案