Nest.js 8.04+TypeORM 0.2.34一对多关联查询返回空数组如何解决
问题根因及解决方案
1. 自定义Repository归属错误
你用于查询章节的getOneChapter方法写在了ParagraphRepository中,该Repository默认绑定的实体是Paragraph,调用createQueryBuilder('chapter')时实际查询的根表是paragraph而非chapter,关联逻辑自然无法匹配。
修复方式:将该查询方法移动到ChapterRepository中,且确认ChapterRepository使用@EntityRepository(Chapter)装饰,正确绑定Chapter实体。
2. 模块未注册关联实体
ChapterModule的TypeOrmModule.forFeature配置仅注册了Chapter实体,TypeORM在当前模块上下文内无法识别Paragraph实体的映射关系,导致关联查询失效。
修复方式:修改chapter.module.ts配置,引入关联的Paragraph实体:
@Module({ imports: [TypeOrmModule.forFeature([Chapter, ChapterRepository, Paragraph])], controllers: [ChapterController], providers: [ChapterService] }) export class ChapterModule {}
3. 关联字段显式映射外键
TypeORM自动生成外键映射可能存在匹配误差,可显式指定外键字段和数据库字段对应,避免映射错误:
// paragraph.entity.ts 修改关联注解 @ManyToOne(type => Chapter , chapter => chapter.paragraph) @JoinColumn({ name: 'chapterId' }) chapter: Chapter;
4. 确认自定义仓库配置正确
检查ChapterRepository的基础配置是否符合TypeORM 0.2.x规范:
import { EntityRepository, Repository } from 'typeorm'; import { Chapter } from './chapter.entity'; @EntityRepository(Chapter) export class ChapterRepository extends Repository<Chapter> {}
完成以上修改后重新测试查询,即可正常返回关联的paragraph数组。
内容的提问来源于stack exchange,提问作者edmond tm
相关产品推荐
相关产品推荐

