【发布时间】: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