【发布时间】:2020-08-14 04:00:48
【问题描述】:
我正在使用 Nest.js,并考虑从 TypeORM 迁移到 Mikro-ORM。我正在使用nestjs-mikro-orm 模块。但我被困在看似非常简单的事情上......
我有 3 个实体,AuthorEntity、BookEntity 和 BookMetadata。在我的Author 模块中,我尝试使用createQueryBuilder 方法离开加入Book 和BookMetadata 表。但是在运行我的查询时,我在Collection<BookEntity> of entity AuthorEntity[3390] not initialized 处遇到错误。但是,Author 表中的列可以很好地检索到。
我的 3 个实体:
@Entity()
@Unique({ properties: ['key'] })
export class AuthorEntity {
@PrimaryKey()
id!: number;
@Property({ length: 255 })
key!: string;
@OneToMany('BookEntity', 'author', { orphanRemoval: true })
books? = new Collection<BookEntity>(this);
}
@Entity()
export class BookEntity {
@PrimaryKey()
id!: number;
@ManyToOne(() => AuthorEntity)
author!: AuthorEntity;
@OneToMany('BookMetadataEntity', 'book', { orphanRemoval: true })
bookMetadata? = new Collection<BookMetadataEntity>(this);
}
@Entity()
@Unique({ properties: ['book', 'localeKey'] })
export class BookMetadataEntity {
@PrimaryKey()
id!: number;
@Property({ length: 5 })
localeKey!: string;
@ManyToOne(() => BookEntity)
book!: BookEntity;
}
以及我运行查询的服务文件:
@Injectable()
export class AuthorService {
constructor(
@InjectRepository(AuthorEntity)
private readonly authorRepository: EntityRepository<AuthorEntity>,
) {}
async findOneByKey(props: { key: string; localeKey: string; }): Promise<AuthorEntity> {
const { key, localeKey } = props;
return this.authorRepository
.createQueryBuilder('a')
.select(['a.*', 'b.*', 'c.*'])
.leftJoin('a.books', 'b')
.leftJoin('b.bookMetadata', 'c')
.where('a.key = ?', [key])
.andWhere('c.localeKey = ?', [localeKey])
.getSingleResult();
}
}
我错过了什么吗?可能不相关,但我也注意到使用 Nest.js 的 TypeORM 用户有 a special autoLoadEntities: true。 Mikro-ORM 有类似的东西吗?谢谢;)
【问题讨论】: