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

在 TypeORM 中如何使用外键查询数据?

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

1个答案

1

在TypeORM中,使用外键查询数据的一个常见场景是通过关联关系来取得相关数据。我们可以通过几种不同的方法来实现这一点,例如使用QueryBuilder、使用find方法中的relations选项或者使用EntityManager。以下是这些方法的具体使用示例:

1. 使用QueryBuilder

假设我们有两个实体:UserPhoto,其中 Photo 实体有一个外键指向 User 实体。我们可以使用QueryBuilder来查询某个用户的所有照片:

typescript
import { getRepository } from "typeorm"; async function findPhotosByUser(userId: number) { const photoRepository = getRepository(Photo); const photos = await photoRepository .createQueryBuilder("photo") .innerJoinAndSelect("photo.user", "user") .where("user.id = :userId", { userId }) .getMany(); return photos; }

在这个例子中,innerJoinAndSelect 方法用于连接 PhotoUser 表,并同时选择 User 表的内容,这样我们就可以直接访问与每张照片关联的用户数据。

2. 使用find方法中的relations选项

另一个查询带有外键的数据方法是在 find 方法中使用 relations 参数。这种方法的代码更为简洁:

typescript
import { getRepository } from "typeorm"; async function findPhotosByUser(userId: number) { const userRepository = getRepository(User); const userWithPhotos = await userRepository.findOne(userId, { relations: ["photos"] }); return userWithPhotos?.photos; }

在这个例子中,我们直接在查询 User 的同时指定了 relations 选项,这会让TypeORM自动加载与该用户相关联的 Photo 数据。

3. 使用EntityManager

如果你想更直接地控制数据库操作,可以使用 EntityManager

typescript
import { getManager } from "typeorm"; async function findPhotosByUser(userId: number) { const entityManager = getManager(); const photos = await entityManager .createQueryBuilder(Photo, "photo") .innerJoinAndSelect("photo.user", "user") .where("user.id = :userId", { userId }) .getMany(); return photos; }

这种方法和使用 getRepository 类似,但它直接使用 EntityManager,这对于一些复杂的查询场景可能会更灵活。

总结

在TypeORM中,使用外键查询数据可以通过多种途径实现,选择合适的方法取决于具体的应用场景和个人偏好。通过以上示例,我们可以看到TypeORM提供了灵活而强大的工具来处理数据库中的关联数据查询。

2024年6月29日 12:07 回复

你的答案