如何在TypeORM中查询@OneToMany关联不为空的记录?
查询拥有非空photos的User实体(TypeORM实现方案)
完全可以通过TypeORM的API实现该需求,无需编写原生SQL,以下是三种常用的实现方式:
方法一:使用QueryBuilder(推荐)
通过内连接(innerJoin)关联Photo表,自动过滤掉没有关联照片的用户,再通过去重确保每个用户只返回一次:
import { getRepository } from "typeorm"; import { User } from "./User"; async function getUsersWithPhotos() { const userRepo = getRepository(User); const users = await userRepo .createQueryBuilder("user") .innerJoin("user.photos", "photo") .distinct(true) .getMany(); return users; }
说明:innerJoin会仅保留存在对应Photo记录的User;添加distinct(true)是避免同一用户因有多张照片而被重复返回。
方法二:使用Exists子查询
通过子查询判断用户是否存在关联的Photo记录,以此作为筛选条件:
import { getRepository, Exists, SelectQueryBuilder } from "typeorm"; import { User } from "./User"; import { Photo } from "./Photo"; async function getUsersWithPhotos() { const userRepo = getRepository(User); const users = await userRepo.find({ where: (qb: SelectQueryBuilder<User>) => { qb.where( new Exists( qb.subQuery() .select("1") .from(Photo, "photo") .where("photo.userId = user.id") ) ); }, }); return users; }
方法三:简化语法(部分TypeORM版本支持)
若你的TypeORM版本较新,可直接使用关联存在的简化判断语法:
import { getRepository } from "typeorm"; import { User } from "./User"; async function getUsersWithPhotos() { const userRepo = getRepository(User); const users = await userRepo.find({ where: { photos: { exists: true } }, }); return users; }
注意:不同TypeORM版本的简化语法可能略有差异,需根据实际使用版本调整。
内容的提问来源于stack exchange,提问作者titusmagnus
相关产品推荐
相关产品推荐

