Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  80] [ 6]  / answers: 1 / hits: 5573  / 4 Years ago, fri, april 24, 2020, 12:00:00

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

More From » node.js

 Answers
2

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

[#4046] Tuesday, April 21, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;