【问题标题】:typeorm self reference one to many counttypeorm 自引用一对多计数
【发布时间】:2021-09-25 01:49:34
【问题描述】:

您好,这是我的 comment.entity.ts


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

  @Column()
  name: string;

  @Column()
  email: string;

  @Column({ type: 'text' })
  body: string;

  @Column()
  type: CommentTypeEnum.POST | CommentTypeEnum.COMMENT;

  @Column({ type: 'boolean', default: false })
  has_parent: boolean;

  @ManyToMany(() => Comment, (comment) => comment.children)
  parent: Comment;

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

如你所见,我有一对多关系的自引用。

我这样获取数据:

  const query = Comment.createQueryBuilder('comment');



    query.andWhere('comment.has_parent = false');

    const comments = await query.orderBy('created_at', 'DESC').getMany();

我想在结果中添加孩子数,我不知道该怎么做。

【问题讨论】:

  • 所以,如果我理解正确,你想获得所有Comment(s) 其中has_parentfalse 并计算有多少children this实体有?
  • @CarloCorradini 是的人

标签: javascript node.js typescript nestjs typeorm


【解决方案1】:

它会像这样获取,它对我有用。

query.loadRelationCountAndMap('comment.childrenCount','comment.children')

【讨论】:

  • query.loadRelationCountAndMap('comment.children', 'comment.children') 给了我错误:TypeError: Cannot read property 'referencedColumn' of undefined.
猜你喜欢
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多