TypeOrm 闭包表保留元素对其自身的引用

问题描述 投票:0回答:1

我在 TypeOrm 中将它与 Nest js 一起使用。面临着在闭包表中创建带有parentId prop的元素时,父子元素之间的关系没有正确保存的问题。在实体本身中,parentId 书写正确。

这是 typeOrm 本身的问题还是我做错了什么?

实体代码:

@Entity({ name: 'cmdb_instance' })
@Tree('closure-table', {
  closureTableName: 'cmdb_instance',
  ancestorColumnName: (column) => 'ancestor_' + column.propertyName,
  descendantColumnName: (column) => 'descendant_' + column.propertyName,
})
export class CmdbInstance extends AbstractEntity {
  @Column({ length: 512 })
  name: string;

  // relate to type
  @ManyToOne(() => CmdbType, (type) => type.instances)
  @JoinColumn({
    name: 'type_id',
  })
  type: CmdbType;

  // tree
  @TreeChildren({ cascade: true })
  children: CmdbInstance[];

  @TreeParent({ onDelete: 'CASCADE' })
  parent: CmdbInstance;

  // horizontal relate
  @OneToMany(() => CmdbInstance, (x) => x.belongsToHorizontal)
  horizontal: CmdbInstance[];

  @ManyToOne(() => CmdbInstance, (x) => x.horizontal)
  @JoinColumn({
    name: 'related_id',
  })
  belongsToHorizontal: CmdbInstance;

  @Column({ nullable: true, name: 'related_id' })
  relatedId: string;
}

服务保存方法:

public async createCmdbInstance(
    payload: CreateCmdbInstanceRequestDto,
  ): Promise<CreateCmdbInstanceResponse> {
    const parent = payload.parentId
      ? await this.cmdbInstanceRepository.findOne({
          where: {
            id: payload.parentId,
          },
        })
      : null;

    const newCmdbInstance = this.cmdbInstanceRepository.create({
      ...payload,
      parent,
    });
    await this.cmdbInstanceRepository.save(newCmdbInstance, {});

    return {
      id: newCmdbInstance.id,
      error: null,
      status: HttpStatus.OK,
    };
  }

请求数据库中的结果:

带有实例表的图像: 带有闭合表的图像:

nestjs typeorm nest
1个回答
0
投票

这里也有同样的问题。有一个小小的区别:我什至无法创建后代,因为(我的实例我使用待办事项)在创建待办事项时,它会自动将待办事项的 id 设置为闭包表中的父级和子级 id

© www.soinside.com 2019 - 2024. All rights reserved.