【问题标题】:getting data in self-referencing relation with TypeORM使用 TypeORM 以自引用关系获取数据
【发布时间】:2021-05-04 12:43:26
【问题描述】:

这是我的实体:

@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
}

假数据:

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

我想检索符合以下条件的行: parentIdNULLstatusCommentStatus.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()

它检索所有行,因为它不检查子项的status 为什么?

任何帮助将不胜感激

【问题讨论】:

    标签: typescript typeorm self-referencing-table


    【解决方案1】:

    您需要为父级及其子级添加两个不同的 where 子句。

    例如-

    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()
    

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多