Search code examples
typescriptone-to-manytypeormmany-to-one

How to reference only one entity in a one-to-many relationship in TypeORM


I'm wondering what's the best way to reference just one related entity instead of all of them in a one to many relationship.

For example, let's say I have a user, and it can have multiple photos. I want each photo to be related to the user, but from the user perspective I only care about one specific photo (the last uploaded one for example).

One approach is:

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    currentPhotoId: number;

    async getCurrentPhoto(): Photo {
        ...
    }

    ...   
}

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => User, user => user.photos)
    user: User;

    ...
}

But, is there a TypeORM-way for doing things like this? For example, it would be nice if it would be an eager solution and won't require another async operation to fetch the related entity.
I'm probably not the first to come up with this requirement, but I haven't found anything, maybe I'm not searching properly.


Solution

  • I think that currentPhotoId should be oneToOne relationship to Photo and on an update of the photo, this id should be updated. Because this way business logic and database schema would be properly separated.