例如:
3桌
user
user_business_lines_business_line
business_line
Run Code Online (Sandbox Code Playgroud)
那些由typeorm声明创建的User
@ManyToMany(type => BusinessLine)
@JoinTable()
businessLines: BusinessLine[]
Run Code Online (Sandbox Code Playgroud)
然后,如何添加列字段,如
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date
Run Code Online (Sandbox Code Playgroud)
到 user_business_lines_business_line
小智 13
无法在自动创建的多对多桥表中添加自定义列。所以创建另一个表并在它们之间给出一对多和多对一的关系。
例如:
三桌
用户 -> 表 1
业务线 -> 表 2
UserBusinessLine -> User 表和 BusinessLine 表之间的桥接表
UserBusinessLine table will contain the foreign key of both parent tables and also we can add custom culomns into it.
Run Code Online (Sandbox Code Playgroud)
在用户表中
@OneToMany(() => UserBusinessLine, (userBusinessLine) => userBusinessLine.user)
public userBusinessLines: UserBusinessLine[];
Run Code Online (Sandbox Code Playgroud)
在业务线表中
@OneToMany(() => UserBusinessLine, (userBusinessLine) => userBusinessLine.businessLine)
public userBusinessLines: UserBusinessLine[];
Run Code Online (Sandbox Code Playgroud)
在 UserBusinessLine 表中
@ManyToOne(() => User, (user) => user.userBusinessLines)
public user: User;
@ManyToOne(() => User, (businessLine) => businessLine.userBusinessLines)
public businessLine: BusinessLine;
// Custom Colums
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date;
Run Code Online (Sandbox Code Playgroud)
所以现在自定义表有 User 表和 BusinessLine 表的外键。还有 CreateddateColumn 和 UpdatedDateColumn
您可以为 ManyToMany 关系指定自定义连接表
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@ManyToMany(type => BusinessLine, businessLine => businessLine.users)
@JoinTable({
name: 'user_business_line',
joinColumn: {
name: 'userId',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'businessLineId',
referencedColumnName: 'id',
},
})
businessLines: BusinessLine[]
}
@Entity('user_business_line')
export class UserBusinessLine {
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date
@Column()
@IsNotEmpty()
@PrimaryColumn()
userId: number;
@Column()
@IsNotEmpty()
@PrimaryColumn()
businessLineId: number;
}
@Entity()
export class BusinessLine {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@ManyToMany(type => User, user => user.businessLines)
users: User[]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6934 次 |
| 最近记录: |