I am currently facing an issue with connecting three entities - Photo, PhotoComment, and PhotoRating. My goal is to allow users to rate a photo, while also enabling multiple comments from various users and multiple ratings (with only one per user). I want the user's rating to be displayed on all comments related to the photos. However, I am struggling to update the rate inside the comments automatically whenever a user changes the photo rate using the ratePhoto
method.
Upon calling the ratePhoto
method, I noticed in PGAdmin that the photoRatingId
is not linked with PhotoComment
and fails to update the rate there. Despite this issue, the ratePhoto
method functions correctly and saves the photo rate appropriately.
My current tech stack includes NestJS, TypeORM, PostgreSQL, and RxJS. I have a strong preference for working with repositories over query builders.
photos.service.ts
public ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable<any> {
return this.getPhoto(photoId).pipe(
switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(
map((photoRating: PhotoRating) => {
if (!photoRating) {
const newRating: PhotoRating = new PhotoRating();
newRating.rate = ratePhotoDto.rate;
newRating.user = user;
newRating.photo = photo;
return this.photoRatingRepository.save(newRating);
}
photoRating.rate = ratePhotoDto.rate;
return this.photoRatingRepository.save(photoRating);
}),
)),
);
}
photo.entity.ts
@Entity()
export class Photo {
//...
@OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)
public photoComments: PhotoComment[];
@OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)
public photoRatings: PhotoRating[];
}
photo-comment.entity.ts
@Entity()
export class PhotoComment {
//...
@ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })
public photo: Photo;
@ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)
@JoinColumn({ name: 'rate' })
public photoRating: PhotoRating;
}
photo-rating.entity.ts
@Entity()
@Unique(['user', 'photo'])
export class PhotoRating {
//...
@Transform(({ value }) => +value)
@Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })
public rate: number;
@ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })
public photo: Photo;
@OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating, { cascade: true })
public photoComment: PhotoComment;
}
What could be causing this issue?