首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在typeorm中创建如何创建多对多关系[NestJS]

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

Stack Overflow用户
提问于 2021-03-31 11:01:02
回答 1查看 632关注 0票数 3

如何在多个关系中保存数据??( user,book (MTM))这里是用户和图书之间的多对多关系。我的发球不正确。另外,我的代码也不能工作。数据存储在book表中。

我需要你的帮助,事前谢谢你。

My Stack => NestJs,TypeORM,MySQL

这是我的实体。enter image description here

user.entity

代码语言:javascript
运行
复制
@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

代码语言:javascript
运行
复制
@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

代码语言:javascript
运行
复制
@UseGuards(JwtAuthGuard)
    @Post('bpc')
    savebpc(@Req() req: any, @Query('title') bookTitle: string){
        return this.BookService.addBpc(req, bookTitle);
    }

book.service.ts

代码语言:javascript
运行
复制
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';
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-31 21:17:52

你需要在user和book中添加许多关系,这是一个使用express和typeorm的例子,但它与nestjs是一样的。

用户实体:

代码语言:javascript
运行
复制
@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[];
}

角色实体:

代码语言:javascript
运行
复制
@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;
}

下面是如何在user_role中保存数据:

代码语言:javascript
运行
复制
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); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66881061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档