简体   繁体   English

使用 TypeORM 以自引用关系获取数据

[英]getting data in self-referencing relation with TypeORM

This is my entity:这是我的实体:

@Entity()
export class Comment extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column({ type: "text" })
    body: string

    @Column()
    displayName: string

    @OneToMany(() => Comment, comment => comment.parent, { eager: true })
    children: Comment[];

    @Column({ nullable: true })
    parentId: number

    @ManyToOne(() => Comment, comment => comment.children)
    @JoinColumn({ name: 'parentId' })
    parent: Comment

    @Column()
    status: CommentStatus
}

export enum CommentStatus {
    Visible = 1,
    InVisible = 2
}

fake data:假数据:

id     parentId     status     body
----------------------------------------
1      NULL         1          body-1
----------------------------------------
2      1            1          body-1-1
----------------------------------------
3      1            2          body-1-2
----------------------------------------
4      1            2          body-1-3

I want to retrieve the rows with the following conditions: parentId is NULL and status is CommentStatus.Visible我想检索具有以下条件的行: parentIdNULL并且statusCommentStatus.Visible

    const query = this.createQueryBuilder('comment')
        .leftJoinAndSelect('comment.children', 'parent')
        .where("comment.parentId IS NULL")
        .andWhere("comment.status = :status", { status: CommentStatus.Visible })

    const comments = await query.getMany()

It retrieves all the rows, because It does not check the status of children items why?它检索所有行,因为它不检查子项的status ,为什么?

any help would be really appreciated任何帮助将非常感激

You need to add two different where clauses for the parent and their children.您需要为父级及其子级添加两个不同的 where 子句。

For example-例如-

const query = this.createQueryBuilder('comment')
    .leftJoinAndSelect('comment.children', 'parent')
    .where("comment.parentId IS NULL")
    .andWhere("comment.status = :status", { status: CommentStatus.Visible })
    .andWhere("parent.status = :status", { status: CommentStatus.Visible })

const comments = await query.getMany()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM