[英]SQL/TypeORM - How do you represent the "many" part of a one-to-many relation as multiple tables?
不知道任何存儲細節,假設我有一個域 object,在 Typescript 中看起來像這樣。
interface Cow {
id: string;
farmer_id: string;
num_spots: number;
}
interface Pig {
id: string;
farmer_id: string;
oink_decibals: number;
}
type Animal = Cow | Pig;
interface Farmer {
id: string;
animal: Animal[];
}
所以Animal
是一種可區分的聯合類型,其中每只動物都具有不同於其他動物的獨特屬性( num_spots
與oink_decibals
)。
我在 SQLite 中考慮建模的方式是 3 個表
用戶 | 奶牛 | 豬 |
---|---|---|
ID | ID | ID |
num_spots | oink_decibals | |
用戶身份 | 用戶身份 |
所以 Farmer -> Animal 對我來說看起來像是一對多的關系,但“多”部分是一種受歧視的聯合類型,分布在多個表中。 我不確定將聯合中的每種類型建模為它自己的單獨表是否是最好的方法,如果是,我不確定如何在 ORM 中表示該關系(在我的例子中是 TypeORM)
@Entity()
class Farmer {
@OneToMany(???)
animals: ????;
}
我知道我可以為每項運動設置單獨的字段
@Entity()
class Farmer {
@OneToMany(() => Cow)
cows: Cow[];
@OneToMany(() => Pig)
pigs: Pig[];
}
但我預計動物的數量會隨着應用程序的發展和演變而增長。 我不希望我的農夫 model 被每只動物淹沒成噸的田地。
所以我想我的問題有兩個部分
您可以使用typeorm-polymorphic
package:
@Entity()
export class Farmer implements PolymorphicChildInterface {
@PolymorphicParent(() => [Cow, Pig])
animal: Cow | Pig;
@Column()
entityId: number;
@Column()
entityType: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.