import { Entity , Column , PrimaryGeneratedColumn } from 'typeorm' ;
@Entity ( )
export class Photo {
@PrimaryGeneratedColumn ( )
id : number ;
@Column ( )
url : string ;
}
// src/tasks/tasks.module.ts
import { Photo } from './entities/photo.entity' ;
// src/tasks/entities/profile.entity.ts
@OneToMany ( ( ) => Photo , ( photo ) => photo . profile )
photos: Photo [ ] ;
// src/tasks/entities/photo.entity.ts
@ManyToOne ( ( ) => Profile , ( profile ) => profile . photos )
@JoinColumn ( { name : 'profile_id' } )
profile: Profile ;
npm run migrations:generate -- add-photos
npm run migrations:run
4 Create service and controllers
nest g service tasks/services/photos --flat
nest g co tasks/controllers/photos --flat
import { Injectable } from '@nestjs/common' ;
import { InjectRepository } from '@nestjs/typeorm' ;
import { Repository } from 'typeorm' ;
import { Photo } from './../entities/photo.entity' ;
import { Profile } from './../entities/profile.entity' ;
@Injectable ( )
export class PhotosService {
constructor (
@InjectRepository ( Photo ) private photoRepo : Repository < Photo > ,
@InjectRepository ( Profile ) private profileRepo : Repository < Profile > ,
) { }
async addPhoto ( data : any ) {
const profile = await this . profileRepo . findOne ( data . profileId ) ;
const newPhoto = new Photo ( ) ;
newPhoto . url = data . url ;
newPhoto . profile = profile ;
return this . photoRepo . save ( newPhoto ) ;
}
}
import { Body , Controller , Post } from '@nestjs/common' ;
import { PhotosService } from './../services/photos.service' ;
@Controller ( 'photos' )
export class PhotosController {
constructor ( private photosService : PhotosService ) { }
@Post ( )
addPhoto ( @Body ( ) body : any ) {
return this . photosService . addPhoto ( body ) ;
}
}
findAll ( ) {
return this . usersRepo . find ( {
relations : [ 'profile' , 'profile.photos' ] ,
} ) ;
}