TypeOrm closure table retains an element's reference to itself

Viewed 33

I use it in TypeOrm along with nest js. Faced with the problem that when creating an element with a parentId prop in the closure table, the relationship between the elements of the parent and the child is not saved correctly. In the entity itself, parentId is written correctly.

Is this a problem with typeOrm itself or am I doing something wrong?

Entity Code:

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

Service save method:

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,
    };
  }

Result in the request database:

Image with instance table: Image with instance table Image with closure table: Image with closure table

0 Answers
Related