Is there an elegant way using TypeORM to find one record in an array of OneToMany relation and assign it to another field in the entitiy?

馋奶兔 提交于 2020-05-13 06:12:11

问题


I'm looking for a way to implement a function, using NestJS and TypeORM, that will find in OneToMany array a specific element and assign that value to another field in the object. And most important: implemented in a single place in the code.

For example:

The Entity profile have an array of photos, one of the photos is the profile picture. I would like to find that photo in the array and assign it to profilePicture if exist, on every select query. is there a way in typeORM to implement that in a single place in the code?

@Entity('profile')
export class Profile extends BaseEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @OneToMany(type => Photo, photo => photo.profile)
    photos?: Photo[];

    profilePicture?: Photo;
}

回答1:


If you use the query builder, you can achieve that by using leftJoinAndMapOne. I just wanted to add an example, but I just found out that the TypeORM docs already have a good solution for your use case:

 const user = await createQueryBuilder("user")
.leftJoinAndMapOne("user.profilePhoto", "user.photos", "photo", "photo.isForProfile = TRUE")
.where("user.name = :name", { name: "Timber" })
.getOne(); 

Edit: Alternatively you can set the profile in your entity using the Afterload decorator:

@AfterLoad()
private setProfile(): void {
    this.photos.forEach((photo) => {
        if (photo.isForProfile) {
            this.photo = value;
        }
    });
}


来源:https://stackoverflow.com/questions/61407959/is-there-an-elegant-way-using-typeorm-to-find-one-record-in-an-array-of-onetoman

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!