Search code examples
postgresqlrelationshipnestjstypeormeager-loading

possible to use eager loading in TypeORM with out defining a relationship?


I want to add Creator Field to all my entities for Authorization purposes . Previously i had a OneToOne relation from every entity to User entity but now i see it is adding Constraint to that tables and eventually a user is not able to create more than a single record . then i think of another Solution it was adding a ManyToOne relationship which it really is but the problem is that you have to add a corresponding field to User for every single entitiy you create . like createdPosts,createdLikes,createdComments and this is also not what i need . there is also another option to add a Creator field with a number type and leftjoin to get user every time is fetch but that add so much burden for maintenance. so is there any built-in solution for this in TypeORM to add a Field Creator to my entities with a User Type and also have the Option to eager load it during gets and Fetchs ?

class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number; 
}
class Service extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    creator: User
 
}

Solution

  • You need many-to-one on your entities that need Creator, but you do not need one-to-many on User for each of those. TypeOrm many-to-one documentation specifically says "If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity."

    You could make this a base class to save typing this for each entity:

    @Entity()
    export class EntityWithCreator extends BaseEntity {
        @ManyToOne(() => User, { eager: true } )
        @JoinColumn()
        creator: User;
    }
    
    @Entity()
    export class Service extends EntityWithCreator {
        // ...
    }