簡體   English   中英

typeorm nestjs 多對多關系插入

[英]typeorm nestjs many to many relationship insert

在使用字符串列表時,我對如何使 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;
  }

}

你不能這樣插入,因為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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM