5

In the Single Table Inheritance Scenario, is there any way to to update a saved BaseEntity object in database as an InheritedEntity object?

Please consider the following scenario:


@Entity()
@TableInheritance({column: {name: 'type', type: "varchar"}})
export class BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;
}


@ChildEntity()
export class ChildEntityOne extends BaseEntity {
  @Column()
  job: string;
}

//
// Create and save a BaseEntity object in database
//
const base = new BaseEntity();
base.title = 'Foo';
await getRepository(BaseEntity).save(base);
//
// Now I have the following in my database
// { id: 1, title: 'Foo', job: null, type: 'BaseEntity' } 
// 

//
// And later I want to query this object form the database and, 
// based on the application logic, cast it to ChideEntityOne and,
// add set its job filed and update it in the database as a ChildEntityOne entity.
//
const entity = await getRepository(BaseEntity).findOne(1);
const childEntity = baseEntity as ChildEntityOne;
childEntity.job = 'Bar';
await getRepository(ChildEntityOne).save(childEntity);

//
// Now I get this in my database:
//
// { id: 1, title: 'Foo', job: null, type: 'BaseEntity' } 
// { id: 2, title: 'Foo', job: 'Bar', type: 'ChildEntityOne' } 
//
//
// But I want to have this in my database: 
// { id: 1, title: 'Foo', job: 'Bar', type: 'ChildEntityOne' } 
//

Is there any clean way to implement this scenario using the TypeORM? Or more importantly is it a logical scenario based on the STI definitions?

Emech
  • 611
  • 1
  • 4
  • 16
  • Did you find a solution? – jsbroks Jul 17 '20 at 21:47
  • 1
    I posted a solution in [the question I asked](https://stackoverflow.com/questions/72529880/updating-an-entitys-type-in-typeorm-single-table-inheritance/72617525#72617525) – Ella Jun 14 '22 at 13:11

0 Answers0