【问题标题】:Loading Relations in Tree Entity : TypeORM在树实体中加载关系:TypeORM
【发布时间】:2021-10-27 23:02:29
【问题描述】:

我对在 TypeORM 中使用树实体有很多疑问, 这是我的 commment.entity.ts

@Entity()
@Tree('closure-table')
export class Comments extends BaseEntity {
  @Column({ nullable: false })
  commentBody: string;

  @ManyToOne(() => User, (user) => user.comments)
  @JoinColumn({ name: 'user_id' })
  user: User;

  @ManyToOne(() => Posts, (post) => post.comments)
  @JoinColumn({ name: 'post_id' })
  post: Posts;

  @TreeChildren()
  children: Comments[];

  @TreeParent()
  parent: Comments;

}

我在这里要做的是,用户可以在Post上创建评论

so, user -> 评论(OneToMany 关系) 并发布 -> 评论(OneToMany 关系)

还有我的post.entity.ts


@Entity('posts')
export class Posts extends FakeBaseEntity {
  @Column({ length: 200, nullable: true })
  caption: string;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'author_id' })
  author: User;

  @OneToMany(() => Comments, (comment) => comment.post)
  comments: Comments[];
}

当我试图获取任何 Post 时,我希望所有的 cmets(即所有的孩子)都与他们关联

我的做法有点像这样,

const posts = await this.postsRepo
      .createQueryBuilder('posts')
      .leftJoinAndSelect('posts.author', 'author')
      .leftJoinAndSelect('posts.comments', 'comments')
      .leftJoinAndSelect('comments.children', 'replies') // gets only one children of it
      .leftJoinAndSelect('comments.user', 'commentUser')
      .where('posts.author = :userid', { userid });

通过这个查询我只能得到孩子,即使它有多个孩子

那么,我如何返回与单个评论(即)关联的所有 cmets 以及它的所有子项?

【问题讨论】:

    标签: javascript typescript nestjs typeorm


    【解决方案1】:
    const posts = await this.postsRepo
          .createQueryBuilder('posts')
          .leftJoinAndSelect('posts.author', 'author')
          .leftJoinAndSelect('posts.comments', 'comments')
          .leftJoinAndSelect('comments.children', 'replies') // gets only one children of it
          .leftJoinAndSelect('comments.user', 'commentUser')
          .where('posts.author = :userid', { userid })   .getRawMany();
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2021-01-05
    • 2019-12-30
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多