【发布时间】:2021-06-27 01:36:59
【问题描述】:
如何以多对多关系保存数据? (用户,书籍(MTM)) 这是用户和图书之间的多对多关系。 我的服务不正确。 另外,我的代码不起作用。 数据存储在 book 表中。
我需要你的帮助,一切 提前谢谢你。
我的堆栈 => NestJs、TypeORM、MySQL
有我的实体。 enter image description here
用户.实体
@Entity('User')
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column()
real_name!: string;
@Column()
nick_name!: string;
@Column()
@IsEmail()
email!: string;
@Column()
password!: string;
@Column()
phone_number!: string;
@Column()
image_url: string;
@BeforeInsert()
async hashPassword() {
this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});
}
}
book.entity
@Entity('Book')
export class Book {
@PrimaryGeneratedColumn()
id!: number;
@Column()
title: string;
@Column()
image_url: string;
@Column()
contents: string;
@Column({ type: 'datetime'})
datetime: string;
@ManyToMany(() => User)
@JoinTable()
users: User[];
}
book.controller.ts
@UseGuards(JwtAuthGuard)
@Post('bpc')
savebpc(@Req() req: any, @Query('title') bookTitle: string){
return this.BookService.addBpc(req, bookTitle);
}
book.service.ts
async addBpc(req: any, bookTitle: string): Promise<any>{
const userId = req.user.id;
const bookId = await getRepository('Book')
.createQueryBuilder('book')
.where({title:bookTitle})
.getRawOne()
if (!bookId){
throw new NotFoundException('Not_found_book');
}
const user = await getRepository('User')
.createQueryBuilder('user')
.where({id: userId})
.getRawOne()
//bookId.user.push(user);
//await this.bookRepository.save(bookId);
let userdata = new User();
userdata.id = user.user_id;
userdata.real_name = user.user_real_name;
userdata.nick_name = user.user_nick_name;
userdata.email = user.user_email;
userdata.password = user.user_password;
userdata.image_url = user.user_image_url;
console.log(userdata);
let bookBpc = new Book();
bookBpc.title = bookId.book_title;
bookBpc.image_url = bookId.book_image_url;
bookBpc.contents = bookId.book_contents;
bookBpc.datetime = bookId.book_datetime;
bookBpc.users = [user];
console.log(bookBpc);
await this.bookRepository.create([bookBpc]);
return 'suceess';
}
【问题讨论】: