Search code examples
typescriptnestjsentitytypeormts-node

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?


Solution

  • 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;
        
    }