TypeORM多对多联接表的额外列

时间:2020-07-15 19:56:58

标签: typescript orm typeorm

我与TypeORM有简单的多对多关系

用户实体

@Entity({ name: 'users' })
export class User {
  @PrimaryColumn()
  id: string;

  @Column()
  email: string;

  @Column()
  password: string;

  @ManyToMany((type) => Organization, (organization) => organization.users)
  @JoinTable({
    name: 'user_organizations',
    joinColumn: {
      name: 'user_id',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'organization_id',
      referencedColumnName: 'id',
    },
  })
  organizations: Organization[];

组织实体

@Entity({ name: 'organizations' })
export class Organization {
  @PrimaryColumn()
  id: string;

  @Column()
  name: string;

  @ManyToMany((type) => User, (user) => user.organizations)
  users: User[];

}

我的目标是创建一个关系,该关系不仅定义哪个用户与哪个组织有关,还应该包含该用户与哪个组织有关的角色的信息。我的想法是为此添加一个额外的role列来扩展关系表。

create table user_organizations(
  user_id varchar(64) not null,
  organization_id varchar(64) not null,
  role varchar(64) not null,
  foreign key (user_id) references users(id),
  foreign key (organization_id) references organizations(id),
);

我的问题是如何在数据库中存储角色。目前我正在做这样的事情。

let user = new User();
let organization = new Organization();
organization.name = name;
organization.users = [user];
organization = await this.organizationRepository.save(organization);

如何通过TypeORM填充role列?

1 个答案:

答案 0 :(得分:1)

解决此类问题的最佳方法是为Role创建一个单独的表,然后在user_organizations中引用该表。

但是请考虑这种情况-如果用户不只是一个角色,该怎么办?它可以并且确实发生。话虽如此,我的建议是处理user_organisations表的外部角色。由于该表为 M2M ,因此主键将是User.IDOrganisation.ID的组合。我的建议是:

  1. 为所有角色(如用户或组织)创建单独的表
  2. RolesUserOrganisations之间创建M2M表
相关问题