S. Karki
S. Karki

Reputation: 498

How to make OneToOne relationship optional for multiple inherited classes?

Suppose I have a class Animal which are inherited by Dog and Cat.

export class Animal extends BaseEntity{
    @PrimaryGeneratedColumn()
    id:number;
}

@Entity()
export class Cat extends Animal{
   ...
}

@Entity()
export class Dog extends Animal{
   ...
}

Now, I want to show a OneToOne relationship with their owner.

@Entity
export class Owner extends BaseEntity{
   ....
 
   @OneToOne()
   pet:???
}

Owner is a class which has an attribute pet that can either be a Cat or a Dog. How can I achieve this using typeorm?


Or am I doing it wrong?

Upvotes: 4

Views: 799

Answers (2)

Pittar ParkHer
Pittar ParkHer

Reputation: 21

You can use @ChildEntity() for children and @Entity() for main class in typeorm.

Upvotes: 2

Aaditya Ghimire
Aaditya Ghimire

Reputation: 58

Here is how you do it


@Entity()
@TableInheritance({ column: { type: "varchar", name: "type" } })
export class Content {
    
    @PrimaryGeneratedColumn()
    id: number;
 
    @Column()
    title: string;
    
    @Column()
    description: string;
    
}

@ChildEntity()
export class Photo extends Content {
    
    @Column()
    size: string;
    
}
@ChildEntity()
export class Question extends Content {
    
    @Column()
    answersCount: number;
    
}
@ChildEntity()
export class Post extends Content {
    
    @Column()
    viewCount: number;
    
}

Upvotes: 3

Related Questions