TypeORM 多对多连接 table 额外的列

TypeORM Many-to-Many join table extra column

我与 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 列来扩展关系 table。

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 列?

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

但是想想这个场景——如果用户不只有一个角色怎么办?它可以而且确实发生了。话虽如此,我的建议是处理 user_organisations table 的 outside 角色。由于 table 是 M2M,主键将是 User.IDOrganisation.ID 的组合。我的建议是:

  1. 为所有角色(如用户或组织)创建单独的table
  2. RolesUserOrganisations
  3. 之间创建 M2M table