我正在使用 Nest.js,并考虑从 TypeORM 迁移到 Mikro-ORM。我正在使用该nestjs-mikro-orm
模块。但我被困在一些看起来很简单的事情上......
我有 3 个实体AuthorEntity
,BookEntity
和BookMetadata
。在我的Author
模块中,我尝试使用该方法左连接Book
和BookMetadata
表createQueryBuilder
。但是在运行我的查询时,我收到一个错误 where 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 用户有一个特殊之处。autoLoadEntities: true
Mikro-ORM 有类似的东西吗?谢谢 ;)