创建controller module service
--no-spec 不生成测试文件
-d 在debug模式运行
nest g co --no-spec -d nest g mo --no-spec nest g s --no-spec
Typeorm联表查询
getAttachment(): Promise<any> {
return this.userRepository.createQueryBuilder()
.leftJoinAndSelect(Article, 'article', 'user.id = article.createBy')
.leftJoinAndSelect(Attachment, 'attachment', 'user.id = attachment.createBy')
.select(`
article.id as id,
article.title as title,
article.content as content,
user.id as userId,
user.nickname as nickname,
user.username as usernmae,
user.avator as avator,
attachment.id as attachmentId,
attachment.originName as fileName,
attachment.size as fileSize,
attachment.filePath as filePath
`)
.getRawMany();
}
在TypeORM中,leftJoinAndSelect 和 leftJoinAndMap 是两种不同的查询构建器方法,它们用于构建JOIN查询,但它们的作用稍有不同。
leftJoinAndSelect: 这个方法用于执行一个左外连接(LEFT JOIN)并立即选择连接的表中的列。所选择的列将直接包含在返回的实体对象中。
示例:
userRepository.createQueryBuilder("user")
.leftJoinAndSelect("user.posts", "post")
.getMany();
在这个例子中,你将获得一个包含用户和他们的帖子的用户实体数组。
leftJoinAndMap: 这个方法也用于执行一个左外连接,但它允许你自定义返回结果的结构。你可以将连接的表映射到实体的一个特定属性中,而不是直接选择列。
它提供了更复杂的结果映射能力,并且允许你对返回的实体的形状进行更细粒度的控制。
示例(映射到一个新属性):
userRepository.createQueryBuilder("user")
.leftJoinAndMapOne("user.postDetails", "user.posts", "post")
.getMany();
在这个例子中,每个用户将拥有一个名为 postDetails 的属性,它包含所有与用户相关联的帖子的信息。
总结:
leftJoinAndSelect 是更简单、更直接的方式,用来将JOIN查询的结果作为实体的一部分返回。
leftJoinAndMap 提供了更大的灵活性和控制,允许你将结果映射到实体的自定义属性中。
这意味着,如果你只需要返回包含所有列的标准实体,leftJoinAndSelect 是一个很好的选择。但如果你需要更复杂或者定制化的结果结构,那么你应该使用 leftJoinAndMap。