天天看點

nestjs+typeorm執行多表查詢

在網上找了很久,都沒有找到合适的control+c的資料,無奈之下,自己隻能啃文檔,全英文的,要了我的老命

我的需求,實作兩個資料表資料連接配接查詢

實作方法

假如有資料表A和資料表B

A和B存在外鍵關系,A表的某個鍵值和B的主鍵成外鍵關系

使用typeorm實作多表查詢,隻需要在建立的A的實體(entity)的檔案中,引用B,然後…

//這個是上面說的A表
	import {
  Column,
  Entity,
  PrimaryGeneratedColumn,
  OneToOne,
  JoinColumn,
  JoinTable,
  OneToMany,
} from 'typeorm';
import { RobotEntity } from '../robot/robot.entity';//這個是上面說的B表

@Entity()
export class TalkMapping {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'project_name', length: 100 })
  gitlabProjectName: string;

  @Column({ name: 'robot_url', length: 500 })
  dingTalkRobotUrl: string;

  @Column({ name: 'robotId' })//外鍵
  robotId: number;
  //下面的代碼是實作多表查詢
  @OneToOne((type) => RobotEntity, (robot) => robot.name, { eager: true })
  @JoinColumn()
  robot: RobotEntity;
}

           
注意:可能大家也看到我的外鍵的name屬性定義的比較奇怪,因為我在使用一對一時,它預設定義的為robotId,我原來定義的robot_id會報錯,然後我企圖修改成我自己定義的,但是沒有搞定,然後屈服了!!!
初次使用nestjs+typeorm,如有錯誤,歡迎指正,也歡迎親們一起探讨!!