I have two entities: User and Photo with relationship OneToMany. One user can have many photos.
User:
@Entity('users')
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Exclude()
@Column()
password: string;
@Column({ default: '' })
avatar: string;
@OneToMany(() => Photo, photo => photo.user, { cascade: true })
photos: Photo[];
}
And Photo:
@Entity('photos')
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@Column({default: ""})
description: string;
@ManyToOne(() => User, user => user.photos)
user: User;
}
So, my question is: how can i add new photo to specific user? I tried to do something like this, but it doesn't work as expected.
@Patch(':id/photos')
addPhoto(@Param('id') id: number, @Body() createPhotoDto: CreatePhotoDto){
return this.userService.createImage(id, createPhotoDto);
}
async createImage(id: number, createPhotoDto: CreatePhotoDto) {
const user = await this.usersRepository.findOne(id);
const newUser = await this.usersRepository.preload({
id: +id,
photos: [...user.photos, createPhotoDto]
});
return this.usersRepository.save(newUser);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…