如何在NestJS中使用MikroORM查询时返回完整的关联实体详情
解决方案:查询图书同步返回完整作者详情
你当前返回的作者仅为Ref { id: 4 }格式,是因为MikroORM默认对关联字段采用懒加载策略,未指定预加载时,关联的author字段仅返回主键引用对象,不会加载完整的作者实体数据。
优先推荐:服务层代码修正
该方案灵活性更高,仅对当前查询生效,不会影响其他Book查询逻辑。只需在find方法的第三个配置参数中添加populate配置,指定预加载author关联即可,修正后代码如下:
@Injectable() export class AppService { constructor( private readonly orm: MikroORM, private readonly em: EntityManager, ) {} async findBooks(): Promise<Book[]> { // 新增populate参数指定预加载author关联字段 const books: Book[] = await this.orm.em.find(Book, {}, { populate: ['author'] }); return books; } }
可选方案:实体注解全局配置
如果所有查询Book的场景都需要自动返回作者详情,可以直接在Book实体的@ManyToOne注解中开启自动预加载,无需每次查询单独配置populate,修改如下:
@Entity() export class Book{ @PrimaryKey() id!: number; @Property() title!: string; // 新增eager: true配置,开启全局自动预加载该关联 @ManyToOne({ entity: () => Author, eager: true }) author!: Author; }
内容的提问来源于stack exchange,提问作者Ashok Kumar
相关产品推荐
相关产品推荐

