给我两分钟,让我教会你Typeorm联表查询

您好, 如果喜欢我的文章或者想上岸大厂,可以关注公众号「量子前端」,将不定期关注推送前端好文、分享就业资料秘籍,也希望有机会一对一帮助你实现梦想

前言

表和表之间都会有关联关系,在Nest项目中我们应该如何联表查询返回数据给客户端呢?

多表关联查询

我们先定义三张表,User、Artcle、Attachment,以User表为主表,以user.id作为外键查询。

定义实体类

User 实体类

typescript 复制代码
// 文件目录: src/entities/user.entity.ts
import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity('user')
export class User {
  @PrimaryColumn()
  id: string;

  @Column()
  nickname: string;

  @Column()
  username: string;

  @Column()
  password: string;

  @Column()
  avator: string;

  @Column()
  email: string;
}

Article 实体类

typescript 复制代码
// 文件目录: src/entities/article.entity.ts
import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity('article')
export class Article {
  @PrimaryColumn()
  id: string;

  @Column()
  title: string;

  @Column()
  link: string;

  @Column()
  fileId: string;

  @Column('text')
  content: string;

  @Column()
  categoryId: string;

  @Column()
  formatId: number;

  @Column()
  originId: number;

  @Column()
  user_id: string;
}

Attachment 实体类

typescript 复制代码
// 文件目录: src/entities/attachment.entity.ts
import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity('attachment')
export class Attachment {
  @PrimaryColumn()
  id: string;

  @Column()
  originName: string;

  @Column()
  size: number;

  @Column()
  filePath: string;

  @Column()
  user_id: string;
}

关联关系

typescript 复制代码
user.id === article.user_id && user.id === attachment.user_id

UserModule 模块文件

typescript 复制代码
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { UserController } from "./user.controller";
import { User } from "../../entities/user.entity";
import { UserService } from "./user.service";
import { Article } from "src/entities/article.entity";
import { Attachment } from "src/entities/attachment.entity";

@Module({
  imports: [TypeOrmModule.forFeature([User, Article, Attachment])],
  controllers: [UserController],
  providers: [UserService]
})
export class UserModule {}

注意:

  1. 这里一定要在 imports 中导入使用的实体类,否则 nestjs 框架无法通过 new 进行实例化相应类型的实例对象

    typescript 复制代码
    @Module({
      imports: [TypeOrmModule.forFeature([User, Article, Attachment])],
      ...
    })

UserService 文件

typescript 复制代码
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Article } from "../../entities/article.entity";
import { Attachment } from "../../entities/attachment.entity";
import { Repository } from "typeorm";
import { User } from "../../entities/user.entity";

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private readonly userRepository: Repository<User>){}
   
  // 三张表关联查询
  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();
  }
}

leftJoinAndMap怎么写?

上面我们用leftJoinAndSelect左连接了Artcle和Attachment两张表,并查询了满足条件的记录,返回了指定的字段。 那用leftJoinAndMap怎么实现呢?leftJoinAndMap 更适合复杂的映射,通常用于将结果映射到实体的某个属性。

typescript 复制代码
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Article } from "../../entities/article.entity";
import { Attachment } from "../../entities/attachment.entity";
import { Repository } from "typeorm";
import { User } from "../../entities/user.entity";

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private readonly userRepository: Repository<User>){}
   
  // 三张表关联查询
  getAttachment(): Promise<any> {
    return this.userRepository.createQueryBuilder('user')
      .leftJoinAndMapOne('user.article', Article, 'article', 'user.id = article.user_id')
      .leftJoinAndMapOne('user.attachment', Attachment, 'attachment', 'user.id = attachment.user_id')
      .select([
        'user.id as userId', 
        'user.nickname as nickname', 
        'user.username as username', 
        'user.avator as avator',
        'article.id as id', 
        'article.title as title', 
        'article.content as content',
        'attachment.id as attachmentId', 
        'attachment.originName as fileName', 
        'attachment.size as fileSize', 
        'attachment.filePath as filePath'
      ])
      .getMany();
  }
}

测试返回的数据如下

json 复制代码
[
    {
        "id": "0fcb8310-9c4a-11ea-9427-017d0539b705",
        "title": "fe'f",
        "content": "<p>微任务</p>",
        "userId": "16ffe4f0-98d0-11ea-adcb-cd4aa44d4464",
        "nickname": "李云龙",
        "usernmae": "wanghailong",
        "avator": "http://192.168.1.101:8765/avator/f360e610-9d80-11ea-9008-019523360f5b.jpg",
        "attachmentId": "03eba231-9bed-11ea-8495-bd633b2536d8",
        "fileName": "附件四 健康承诺书.jpg",
        "fileSize": 139981,
        "filePath": "E:\Practices\workspace-koa2\whl-blog\admin\attachment\article\03eba230-9bed-11ea-8495-bd633b2536d8.jpg"
    },
    ...
]

leftJoinAndSelect和leftJoinAndMap的区别?

在TypeORM中,leftJoinAndSelectleftJoinAndMap 是两种不同的查询构建器方法,它们用于构建JOIN查询,但它们的作用稍有不同。

  1. leftJoinAndSelect: 这个方法用于执行一个左外连接(LEFT JOIN)并立即选择连接的表中的列。所选择的列将直接包含在返回的实体对象中。

示例:

typescript 复制代码
userRepository.createQueryBuilder("user")
    .leftJoinAndSelect("user.posts", "post")
    .getMany();

在这个例子中,你将获得一个包含用户和他们的帖子的用户实体数组。

  1. leftJoinAndMap: 这个方法也用于执行一个左外连接,但它允许你自定义返回结果的结构。你可以将连接的表映射到实体的一个特定属性中,而不是直接选择列。

它提供了更复杂的结果映射能力,并且允许你对返回的实体的形状进行更细粒度的控制。

示例(映射到一个新属性):

typescript 复制代码
userRepository.createQueryBuilder("user")
    .leftJoinAndMapOne("user.postDetails", "user.posts", "post")
    .getMany();

在这个例子中,每个用户将拥有一个名为 postDetails 的属性,它包含所有与用户相关联的帖子的信息。

总结:

  • leftJoinAndSelect 是更简单、更直接的方式,用来将JOIN查询的结果作为实体的一部分返回。
  • leftJoinAndMap 提供了更大的灵活性和控制,允许你将结果映射到实体的自定义属性中。

这意味着,如果你只需要返回包含所有列的标准实体,leftJoinAndSelect 是一个很好的选择。但如果你需要更复杂或者定制化的结果结构,那么你应该使用 leftJoinAndMap

到这里文章就结束了,简单介绍了通过Typeorm在实际业务场景中接触最多的链表查询,希望对你有帮助。

如果喜欢我的文章或者想上岸大厂,可以关注公众号「量子前端」,将不定期关注推送前端好文、分享就业资料秘籍,也希望有机会一对一帮助你实现梦想。

相关推荐
bug菌21 分钟前
Java GUI编程进阶:多线程与并发处理的实战指南
java·后端·java ee
Манго нектар25 分钟前
JavaScript for循环语句
开发语言·前端·javascript
蒲公英100132 分钟前
vue3学习:axios输入城市名称查询该城市天气
前端·vue.js·学习
天涯学馆1 小时前
Deno与Secure TypeScript:安全的后端开发
前端·typescript·deno
以对_1 小时前
uview表单校验不生效问题
前端·uni-app
夜月行者2 小时前
如何使用ssm实现基于SSM的宠物服务平台的设计与实现+vue
java·后端·ssm
程序猿小D2 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
Yvemil72 小时前
RabbitMQ 入门到精通指南
开发语言·后端·ruby
sdg_advance2 小时前
Spring Cloud之OpenFeign的具体实践
后端·spring cloud·openfeign
奔跑吧邓邓子2 小时前
npm包管理深度探索:从基础到进阶全面教程!
前端·npm·node.js