Update an entity type in Single Table Inheritance

Viewed 721

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?

0 Answers
Related