问题
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