Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - How to add create an entity inside another entity (NestJS)?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What I got from the CreatePhotoDto that you save the image and bind it with the user,
one of the easiest way to do it, First declare you imageRepository in your service then :

    async createImage(id: number, createPhotoDto: CreatePhotoDto) {
     const user = await this.usersRepository.findOne(id);
      
     return   await this.imageRepository.save({url:createPhotoDto.url,user:user});
    // if you want to return the user with the image added you make another find with the relation  exp:
   //  return  await this.usersRepository.findOne(id,{ relations: ['photos'],});
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...