使用 TypeORM 和 NestJS 保存多对多关系的最佳方法是什么?
所以我有两个实体,用户
和角色
,它们之间具有多对多
关系。user.entity.ts
@Entity()
@ObjectType()
export class User {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [Role])
@ManyToMany(() => Role, (role) => role.users, {
cascade: true,
lazy: true,
})
@JoinTable()
roles!: Array<Role>;
}
// Deleting the unnecessary properties for readability
role.entity.ts
@Entity()
@ObjectType()
export class Role {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [User])
@ManyToMany(() => User, (user) => user.roles, {
lazy: true,
})
users: Promise<Array<User>>;
@Field(() => String)
@CreateDateColumn()
createdAt: Date;
}
我面临的问题是,当我必须创建一个新的用户,我必须首先从 DTO 中提取角色 ID,为每个 ID 获取数据库中的角色对象,然后在保存之前手动将其连接到用户对象。
const {roleIds} = createUserInput;
const roles = roleIds.map(async (id) => await roleService.findById(id))
const user = this.userRepository.create({...createUserInput, roles});
return this.userRepository.save(user);
这一切都工作正常,但我只是好奇是否有一种方法可以使其工作而无需进行额外的调用和手动接线。如果我可以传入 roleIds,它就会神奇地自动解析它。像这样的东西:
const user = this.userRepository.create({...createUserInput, roleIds});
So I have two entities, User
and Role
with Many-To-Many
relationship between them.
user.entity.ts
@Entity()
@ObjectType()
export class User {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [Role])
@ManyToMany(() => Role, (role) => role.users, {
cascade: true,
lazy: true,
})
@JoinTable()
roles!: Array<Role>;
}
// Deleting the unnecessary properties for readability
role.entity.ts
@Entity()
@ObjectType()
export class Role {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [User])
@ManyToMany(() => User, (user) => user.roles, {
lazy: true,
})
users: Promise<Array<User>>;
@Field(() => String)
@CreateDateColumn()
createdAt: Date;
}
The problem I am facing is that when I have to create a new User, I have to first extract the role ids from the DTO, fetch for each ID the role object in the database and then wire it to the user object manually before saving.
const {roleIds} = createUserInput;
const roles = roleIds.map(async (id) => await roleService.findById(id))
const user = this.userRepository.create({...createUserInput, roles});
return this.userRepository.save(user);
And this is all working fine, but I just am curious if there is a way to get this to work without making the extra calls and manual wiring. If I can just pass in the roleIds and it magically auto resolves it. Something like this:
const user = this.userRepository.create({...createUserInput, roleIds});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论