Typeorm-如何向表中添加额外的字段? [英] typeorm - how to add extra field to "many to many" table?

查看:19
本文介绍了Typeorm-如何向表中添加额外的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

推荐答案

无法在自动创建的多对多桥接表中添加自定义列。因此,创建另一个表,并在它们之间提供一对多和多对一关系。

例如:

三张表

用户-&>表1

BusinessLine->;表2

UserBusinessLine-&>用户表和BusinessLine表之间的桥接表

UserBusinessLine table will contain the foreign key of both parent tables and also we can add custom columns into it.

在用户表中

@OneToMany(() => UserBusinessLine, (userBusinessLine) => userBusinessLine.user)
public userBusinessLines: UserBusinessLine[];

在Business Line表中

@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

这篇关于Typeorm-如何向表中添加额外的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆