【发布时间】: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