数据关系
两表的关联关系,可以使用中间表直接定义所有关系,包括一对一、一对多、多对一、多对多。这样可以避免使用时需要太多的知识储备,造成混乱。
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
用于关联查询