如何使用 @Afterload 保存列,嵌套关系 TypeORM

时间:2021-04-15 06:35:10

标签: nested typeorm relation

我想在我的用户个人资料实体中输入帖子数量。

  • user_profile.entity.ts
@Entity()
@Unique(['username'])
export class UserProfile {
  /** Columns */
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;
 
  @Column('timestamptz')
  @CreateDateColumn()
  readonly created_at: Date;
 
  @Column('timestamptz')
  @UpdateDateColumn()
  readonly updated_at: Date;
 
  @ApiProperty()
  @Column({ length: 255 })
  @IsString()
  @Length(3, 50)
  username: string;
 
  @Column()
  post_count: number;
 
  @ApiProperty({ readOnly: true })
  @Column('uuid')
  @IsUUID('4')
  user_id: string;
 
  @ApiProperty({ readOnly: true })
  @Column({ default: 0, nullable: true })
  @IsOptional()
  exp?: number;
 
  @ApiProperty({ readOnly: true })
  @Column({ default: 1, nullable: true })
  @IsOptional()
  level?: number;
 
  /** Relations */
  @OneToOne((type) => User, (user) => user.profile, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: User;
 
  // ** Hooks
 
  @AfterLoad()
  updatePostCount() {
this.post_count = this.user.posts.length;
  }
}

  • user.entity.ts
@Entity()
@Unique(['email'])
@Check(`
  COALESCE((provider = 'local')::integer, 0) 
  + 
  COALESCE(LENGTH(social_id::text)::boolean::integer, 0)
  = 1
`)
export class User {
  /** Columns */
 
  @ApiProperty()
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;
 
  @ApiProperty()
  @Column('timestamptz')
  @CreateDateColumn()
  readonly created_at: Date;
 
  @ApiProperty()
  @Column('timestamptz')
  @UpdateDateColumn()
  readonly updated_at: Date;
 
  @ApiProperty()
  @Column({ length: 255 })
  @IsEmail()
  email: string;
 
  /** Relations */
 
  @OneToMany((type) => Post, (post) => post.author)
  posts: Post[];
 
  @ApiProperty()
  @OneToOne((type) => UserProfile, (userProfile) => userProfile.user, {
    cascade: true,
  })
  profile: UserProfile;
 
  @AfterLoad()
  asdfasdf() {
    console.log('유저 entity :');
  }
}

  • post.entity.ts
@Entity()
export class Post {
  /** Columns */
 
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;
 
  @Column('timestamptz')
  @CreateDateColumn()
  readonly created_at: Date;
 
  @Column('timestamptz')
  @UpdateDateColumn()
  readonly updated_at: Date;
 
  @ApiProperty()
  @Column({ length: 255 })
  @IsString()
  title: string;
 
  @ApiProperty()
  @Column('text')
  @IsString()
  contents: string;
 
  @ApiProperty({ readOnly: true })
  @Column('uuid')
  @IsUUID('4')
  user_id: string;
 
  /** Relations */
  @ManyToOne((type) => User, (user) => user.posts, {
    cascade: true,
    // eager: true,
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  author: User;
}

  • users.service.ts

  async getMyUser(user_id: string) {
    const test = await this.userProfileRepository
      .createQueryBuilder('user_profile')
      .leftJoinAndSelect('user_profile.user', 'user')
      .leftJoinAndSelect('user.posts', 'posts')
      .where('user.id = :id', { id: user_id })
      .getOne();

    return test;
  }

  async getUserProfile(user_id: string): Promise<UserProfileResponseDto> {
    try {
      const user = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.profile', 'user_profile')
        .leftJoinAndSelect('user.followers', 'followers')
        .leftJoinAndSelect('user.following', 'following')
        .leftJoinAndSelect('user.posts', 'posts')
        .where('user.id = :id', { id: user_id })
        .getOne();

      if (!user) {
        throw new Error();
      }
      return {
        profile: user.profile,
        followers: user.followers.length,
        following: user.following.length,
        posts: user.posts.length,
      };
    } catch (err) {
      throw new BadRequestException('Invalid user_id');
    }
  }

user_profile 实体中,我使用了 @Afterload

当我使用 userPrifileRepository(getMyUser) 时,输出很好, 但是如果我使用 userRepository(getUserProfile),它就不会出现。 (this.userthis.user.posts.length 被打印为未定义。)

即使输出很好,也无法保存。 this.post_count = this.user.posts.length

0 个答案:

没有答案
相关问题