typeorm關聯查詢


數據關系

兩表的關聯關系,可以使用中間表直接定義所有關系,包括一對一、一對多、多對一、多對多。這樣可以避免使用時需要太多的知識儲備,造成混亂。

TypeORM定義

舉例:

table1: {table1_id: number}
table2: {table2_id: number}
table_relation:{table1_id: number, table2_id: number}

上述的結構中,table1與table2,都與table_relation為一對多的關系。反之,table_relation與兩表為多對一。

所有需要在table1與table2中定義OneToMany字段,在table_relation中定義ManyToOne字段:

table1: {
      @PrimaryGeneratedColumn()
      table1_id: number

      @OneToMany(() => TableRelationEntity, (tableRelation) => {tableRelation.table1})
      @JoinTable()
      @JoinColumn({ name: 'table1_id' })
      table2: TableRelationEntity[]
}

table2: {
      @PrimaryGeneratedColumn()
      table2_id: number

      @OneToMany(() => TableRelationEntity, (tableRelation) => {tableRelation.table2})
      @JoinTable()
      @JoinColumn({ name: 'table2_id' })
      table1: TableRelationEntity[]
}

table_relation: {
      @PrimaryGeneratedColumn()
      table1_table2_id: number
      table1_id: number
      table2_id: number

      @ManyToOne(() => Table1Entity, (table1) => {table1.table2})
      @JoinTable()
      @JoinColumn({ name: 'table1_id' })
      table1: Table1Entity

      @ManyToOne(() => Table2Entity, (table2) => {table2.table1})
      @JoinTable()
      @JoinColumn({ name: 'table2_id' })
      table2: Table2Entity
}

此時就可以使用createQueryBuilder用於關聯查詢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM