在单表继承场景中,有没有办法将数据库中保存的 BaseEntity 对象更新为 InheritedEntity 对象?
请考虑以下场景:
@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' }
//
Run Code Online (Sandbox Code Playgroud)
有没有什么干净的方法可以使用 TypeORM 来实现这个场景?或者更重要的是,它是基于 STI 定义的逻辑场景吗?
| 归档时间: |
|
| 查看次数: |
1228 次 |
| 最近记录: |