Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
S. Karki Avatar asked Sep 20 '25 23:09

S. Karki


1 Answers

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;
    
}
like image 178
Aaditya Ghimire Avatar answered Sep 22 '25 14:09

Aaditya Ghimire