例如:
3张桌子
user
user_business_lines_business_line
business_line
由typeorm
创建并在User
中声明的内容
@ManyToMany(type => BusinessLine)
@JoinTable()
businessLines: BusinessLine[]
然后,如何添加列字段,如
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date
到user_business_lines_business_line
答案 0 :(得分:1)
您可以为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[]
}
答案 1 :(得分:0)
不可能在自动创建的多对多桥接表中添加自定义列。因此,创建另一个表并在它们之间建立一对多和多对一的关系。
例如:
三张桌子
用户->表1
BusinessLine->表2
UserBusinessLine -> User表和BusinessLine表之间的桥接表
UserBusinessLine表将包含两个父表的外键,我们也可以在其中添加自定义的culomns。
在用户表中
@OneToMany(() => UserBusinessLine, (userBusinessLine) => userBusinessLine.user)
public userBusinessLines: UserBusinessLine[];
在BusinessLine表中
@OneToMany(() => UserBusinessLine, (userBusinessLine) => userBusinessLine.businessLine)
public userBusinessLines: UserBusinessLine[];
在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;
因此,现在定制表具有User表和BusinessLine表的外键。还有CreateddateColumn和UpdatedDateColumn
答案 2 :(得分:0)
例如,如果仅用于createdAt
时间戳,则可以使用这样的迁移(我正在使用Postgres)在user_business_lines_business_line
表中添加额外的列:
ALTER TABLE "user_business_lines_business_line" ADD "createdAt" TIMESTAMP NOT NULL DEFAULT LOCALTIMESTAMP