Mysql 如何创建如何在typeorm中创建多对多关系[NestJS]

Mysql 如何创建如何在typeorm中创建多对多关系[NestJS],mysql,nestjs,typeorm,Mysql,Nestjs,Typeorm,如何在多个关系中保存数据?? (用户、书籍(MTM)) 这里是用户和书籍之间的多对多关系。 我的发球不正确。 而且,我的代码不起作用。 数据存储在book表中 我需要你的帮助,一切 先谢谢你 My Stack=>NestJs、TypeORM、MySQL 有我的实体。 用户实体 @Entity('User') export class User { @PrimaryGeneratedColumn() id!: number; @Column() real_nam

如何在多个关系中保存数据?? (用户、书籍(MTM)) 这里是用户和书籍之间的多对多关系。 我的发球不正确。 而且,我的代码不起作用。 数据存储在book表中

我需要你的帮助,一切 先谢谢你

My Stack=>NestJs、TypeORM、MySQL

有我的实体。

用户实体

@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});
    }
}
图书实体

@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);
    }
图书服务

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';
    }
async addBpc(请求:any,书名:string):承诺{
const userId=req.user.id;
const bookId=wait getRepository('Book')
.createQueryBuilder('book')
.where({title:bookTitle})
.getRawOne()
如果(!bookId){
抛出newnotfoundexception('Not_found_book');
}
const user=await getRepository('user'))
.createQueryBuilder(“用户”)
.where({id:userId})
.getRawOne()
//bookId.user.push(用户);
//等待这个.bookRepository.save(bookId);
让userdata=newuser();
userdata.id=user.user\u id;
userdata.real\u name=user.user\u real\u name;
userdata.nick\u name=user.user\u nick\u name;
userdata.email=user.user\u email;
userdata.password=user.user\u密码;
userdata.image\u url=user.user\u image\u url;
console.log(userdata);
let bookBpc=新书();
bookBpc.title=bookId.book\u title;
bookBpc.image\u url=bookId.book\u image\u url;
bookBpc.contents=bookId.book\u contents;
bookBpc.datetime=bookId.book\u datetime;
bookBpc.users=[user];
控制台日志(bookBpc);
等待这个.bookRepository.create([bookBpc]);
返回“成功”;
}

您需要在user和book中添加manytomy关系,下面是一个使用express和typeorm的示例,但与nestjs相同

用户实体:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;
  @Column({ type: 'varchar', nullable: false, unique: true })
  username: string;
  // we need to add a default password and get it form the .env file
  @Column({ type: 'varchar', nullable: true, default: '' })
  password: string;
  @Column({ type: 'varchar', nullable: true })
  firstname: string;
  @Column({ type: 'varchar', nullable: true })
  lastname: string;
  @Column({ type: 'varchar', nullable: false })
  email: string;
  @Column({ type: 'boolean', nullable: true, default: false })
  connected: boolean;
  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;

  // new properties
  @Column({ name: 'login_attempts', type: 'int', default: 0, nullable: true })
  loginAttempts: number;
  @Column({ name: 'lock_until', type: 'bigint', default: 0, nullable: true })
  lockUntil: number;

  //Many-to-many relation with role
  @ManyToMany((type) => Role, {
    cascade: true,
  })
  @JoinTable({
    name: "users_roles",
    joinColumn: { name: "userId", referencedColumnName: "id" },
    inverseJoinColumn: { name: "roleId" }
  })
  roles: Role[];
}
角色实体:

@Entity()
export class Role {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', nullable: false, unique: true })
  profile: string;

  @Column({ type: 'varchar', nullable: false })
  description: string;

  //Many-to-many relation with user
  @ManyToMany((type) => User, (user) => user.roles)
  users: User[];
  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;
}
以下是如何以用户角色保存数据:

let entity = await this.userRepository.create(data); //here you create new dataobject that contain user columns 

  let entity2 = { ...entity, roles: data.selectedRoles } // you have to add the association roles here 

  const user = await this.userRepository.save(entity2); 

非常感谢您在百忙之中给出的答案。我从答案中得到了一个提示,并用下面的代码解决了它。尽管它看起来像一条捷径,但这并不重要。等待(bookBpc)的getConnection().createQueryBuilder()关系(Book,“users”)。添加(userdata);