【问题标题】:typeorm nestjs many to many relationship inserttypeorm nestjs 多对多关系插入
【发布时间】:2020-09-01 11:55:41
【问题描述】:

我对如何在使用字符串列表时使 typeorm 多对多关系商店工作感到完全困惑。我已经查看了文档和解决方案的数量,但我似乎无法让它发挥作用。创建组工作正常。

但是更新关系表groups_users 不起作用

curl --location --request POST 'https://localhost/api/group' \
--header 'Content-Type: application/json' \
--data-raw '{
    "groupName": "group-name",
    "users": ['user1', 'user2', 'user2'] // User as strings. NOT ids
}'

// Groups.service.ts

export class GroupsService {
  constructor(
    @Inject(REQUEST) private readonly request: Request,
    @InjectRepository(GroupsEntity)
    private readonly groupsRepository: Repository<GroupsEntity>,
    @InjectRepository(UsersEntity)
    private readonly usersRepository: Repository<UsersEntity>,
  ) {}

  public async createGroup(
    creategroupsdto: CreateGroupsDto,
  ): Promise<InsertResult> {

    // Handle duplicate key error message
    // right now it throws a server error
    const { groupName, users } = creategroupsdto;
    return await this.groupsRepository.insert(new GroupsEntity(groupName, users));
  }
@Entity('groups')
export class GroupsEntity {
  @PrimaryGeneratedColumn() public readonly Id?: number;
  @Column('varchar', { unique: true }) public readonly groupName: string;

  @ManyToMany((type) => UsersEntity, (users) => users.groups, { cascade: true })
  @JoinTable({ name: 'groups_users' })
  users: UsersEntity[];

  constructor(
    groupName: string,
    users: UsersEntity[],
  ) {
    this.groupName= groupName;
    this.users = users;
  }
}

export class UsersEntity {
  @PrimaryGeneratedColumn() public readonly Id?: number;
  @Column('varchar', { unique: true }) public readonly name: string;
  @Column('varchar', { length: 2048, nullable: true }) public readonly userKey: string;

  @OneToMany((type) => ClientsEntity, (client) => client.users, { cascade: true })
  @JoinColumn({ name: 'users_clients' })
  clients: Clients[];

  @ManyToMany((type) => GroupsEntity, (group) => group.Id, { cascade: false })
  @JoinTable({ name: 'groups_users' })
  groups: GroupsEntity[];

  constructor(
    name: string,
    userKey: string,
  ) {
    this.name = name;
    this.userKey = userKey;
  }

}

【问题讨论】:

    标签: javascript sql typescript nestjs typeorm


    【解决方案1】:

    您不能这样插入,因为group.users 想要一个用户数组,而您正在向它提供一个字符串数组。您可以执行以下操作(丑陋、超简化并使用 AR 使其更具可读性,恕我直言,但已经过了凌晨 2 点,我只想明白这一点)

    let groupUsers: User[] = [];
    
    for (const username of creategroupsdto.users) {
        const user: User = await yourMethodToFetchAUserByName(username)
        groupUsers.push(user);
    }
    
    group.users = groupUsers;
    await group.save();
    

    【讨论】:

    • 我的理解是我会提供这种关系是如何建立的,例如我可以提供属性值。和 typeOrm OneToMany 装饰器将描述这种关系,例如根据属性值映射 id(例如,用户/组名称作为字符串),然后它会为我 CRUD 关系表 groups_users。为什么会有一个装饰器,然后还有我自己的方法yourMethodToFetchAUserByName
    • TypeORM 应该仅在您提供和标识符时才获取​​相关实体。不幸的是,您的用户名,即使是唯一的,也不能被 orm 视为标识符。
    • 我不能用@unique@PrimaryColumn() 来定义它作为一个标识符吗?
    猜你喜欢
    • 2020-08-29
    • 2020-06-29
    • 2022-01-02
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2021-04-23
    • 2021-10-17
    • 2020-12-03
    相关资源
    最近更新 更多