typeorm 多表关联查询

关联关系

user.id === host.createBy && user.id === micro.createBy

UserModule 模块文件

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 { Host } from "src/entities/host.entity";
import { Micro } from "src/entities/micro.entity";

@Module({
  // 这里一定要在 imports 中导入使用的实体类,否则 nestjs 框架无法通过 new 进行实例化相应类型的实例对象
  imports: [TypeOrmModule.forFeature([User, Host, Micro])],
  controllers: [UserController],
  providers: [UserService]
})
export class UserModule {}

UserService 文件

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Host } from "../../entities/article.entity";
import { Micro } from "../../entities/attachment.entity";
import { User } from "../../entities/user.entity";

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private readonly userRepository: Repository<User>){}

  // 三张表关联查询
  getMicro(): Promise<any> {
    return this.userRepository.createQueryBuilder()
      .leftJoinAndSelect(Host, 'host', 'user.id = host.createBy')
      .leftJoinAndSelect(Micro, 'micro', 'user.id = micro.createBy')
      .select(`
        micro.id as id,
        micro.title as title,
        micro.content as content,
        user.id as userId,
        user.username as usernmae,
        micro.id as microId,
        micro.originName as fileName,
        micro.size as fileSize,
        micro.filePath as filePath
      `)
      .getRawMany();
  }
}

测试返回的数据如下

[
    {
        "id": "0fcb8310-9c4a-11ea-9427-017d0539b705",
        "title": "fe'f",
        "content": "<p>微任务</p>",
        "userId": "16ffe4f0-98d0-11ea-adcb-cd4aa44d4464",
        "nickname": "李云龙",
        "usernmae": "wanghailong",
        "microId": "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"
    },
    ...
]

posted @ 2022-05-07 17:06  王猪猴  阅读(1466)  评论(0编辑  收藏  举报