typeorm get all comments and count the replies

13 views Asked by At

I have an enity like this:

@Entity()
export class CommentEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @DeleteDateColumn()
  deletedAt: Date;

  @Column({default: null})
  parentId: string;

  @Column({ default: null })
  comment: string;

  @Column({type: "enum", enum: CommentTargetType, default: null})
  targetType: CommentTargetType

  @Column()
  targetId: string;

  @Column({default: null})
  rating: number;

  repliesCount: number

  @ManyToOne(() => UserEntity, (user) => user.comments)
  author: UserEntity;

  @OneToMany(() => VoteEntity, (vote) => vote.comment)
  votes: Array<VoteEntity>

//   @ManyToOne(() => UserEntity, (author) => author.comments)
//   author: UserEntity;

  constructor(partial: Partial<CommentEntity>) {
    Object.assign(this, partial);
  }

}

I want to get all comments for a given targetId and count the number of answers to that comment. Currently I do only the first part (i.e. getting all 'main' comment with parentId equal to null) but I dont know how to do the second part i.e. add a repliesCount column using queryBuidler. Then I could use this repliesCount in orderBy clause.

    const query = this._commentRepository.createQueryBuilder('comment');
    query.leftJoinAndSelect('comment.author', 'author');
    query.leftJoinAndSelect('comment.votes', 'votes');
    query.leftJoinAndSelect('votes.author', 'votes_author');
    query.where('comment.targetId = :id', { id: id });
    query.andWhere('comment.parentId is NULL');
0

There are 0 answers