NestJS中TypeORM查询存在记录却返回null问题求助
NestJS + TypeORM 查询部分ID返回null的原因及解决方案
问题根源
你当前的查询条件存在关键问题:在where中直接指定partecipanti:{deletedAt: IsNull()}时,TypeORM会将其转换为内连接查询。这意味着只有当Evento存在至少一条未被软删除(deletedAt为null)的partecipanti关联记录时,才会返回数据。如果某个Evento的所有partecipanti都被软删除,或者根本没有关联的partecipanti,查询就会返回null。
解决方案
改用QueryBuilder实现左连接+关联过滤,这样即使没有符合条件的partecipanti,只要Evento本身存在,就能正常返回数据。修改后的代码如下:
async findByIdentificativo(id: string): Promise<Evento> { console.log(id); return this.eventoRepository.createQueryBuilder('evento') // 左连接并过滤未被软删除的partecipanti .leftJoinAndSelect('evento.partecipanti', 'partecipanti', 'partecipanti.deletedAt IS NULL') // 其他关联查询保持原样 .leftJoinAndSelect('evento.campionato', 'campionato') .leftJoinAndSelect('evento.giudice', 'giudice') .leftJoinAndSelect('evento.impiantoLuogo', 'impiantoLuogo') .leftJoinAndSelect('impiantoLuogo.enteId', 'enteId') .leftJoinAndSelect('enteId.enteId', 'enteId2') .leftJoinAndSelect('evento.disciplinaEvento', 'disciplinaEvento') .leftJoinAndSelect('disciplinaEvento.specialita', 'specialita') .leftJoinAndSelect('specialita.categorie', 'categorie') .leftJoinAndSelect('partecipanti.associato', 'associato') .leftJoinAndSelect('associato.persona', 'persona') .leftJoinAndSelect('giudice.persona', 'giudicePersona') .leftJoinAndSelect('associato.indiceAssociato', 'indiceAssociato') .leftJoinAndSelect('evento.gareCategorie', 'gareCategorie') .leftJoinAndSelect('gareCategorie.categoria', 'categoria') .leftJoinAndSelect('categoria.idSpecialita', 'idSpecialita') // 指定主实体的查询条件 .where('evento.identificativo = :id', { id }) .getOneOrFail(); }
额外检查点
- 验证数据:针对返回null的ID,直接查询数据库的
Evento表,确认该identificativo对应的记录是否存在;再检查关联的partecipanti记录,看是否全部被软删除或无关联记录。 - 冗余代码优化:原代码中
return await evento;是多余的,evento已经是await后的结果,直接return evento;即可。
内容的提问来源于stack exchange,提问作者SIm Io
相关产品推荐
相关产品推荐

