import { Entity , PrimaryGeneratedColumn , Column } from 'typeorm' ;
@Entity ( )
export class Category {
@PrimaryGeneratedColumn ( )
id : number ;
@Column ( )
name : string ;
}
// src/tasks/tasks.module.ts
import { Category } from './entities/category.entity' ;
// src/tasks/entities/task.entity.ts
@ManyToMany ( ( ) => Category )
@JoinTable ( )
categories: Category [ ] ;
// src/tasks/entities/category.entity.ts
@ManyToMany ( ( ) => Task , ( task ) => task . categories )
tasks: Task [ ] ;
// src/tasks/entities/task.entity.ts
@ManyToMany ( ( ) => Category , ( category ) => category . tasks )
@JoinTable ( {
name : 'tasks_categories' ,
joinColumn : {
name : 'task_id' ,
} ,
inverseJoinColumn : {
name : 'category_id' ,
} ,
} )
categories : Category [ ] ;
npm run migrations:generate -- categories
npm run migrations:run
4 Create service and controllers
nest g service tasks/services/categories --flat
nest g co tasks/controllers/categories --flat
import { Injectable } from '@nestjs/common' ;
import { InjectRepository } from '@nestjs/typeorm' ;
import { Repository } from 'typeorm' ;
import { Category } from './../entities/category.entity' ;
@Injectable ( )
export class CategoriesService {
constructor (
@InjectRepository ( Category ) private categoryRepo : Repository < Category > ,
) { }
create ( body : any ) {
const category = this . categoryRepo . create ( body ) ;
return this . categoryRepo . save ( category ) ;
}
}
import { Controller , Post , Body } from '@nestjs/common' ;
import { CategoriesService } from './../services/categories.service' ;
@Controller ( 'categories' )
export class CategoriesController {
constructor ( private categoriesService : CategoriesService ) { }
@Post ( )
addPhoto ( @Body ( ) body : any ) {
return this . categoriesService . create ( body ) ;
}
}
@InjectRepository ( Category ) private categoryRepo: Repository < Category > ,
async create ( body : any ) {
const newTask = new Task ( ) ;
newTask . name = body . name ;
const categories = await this . categoryRepo . findByIds ( body . categoriesIds ) ;
newTask . categories = categories ;
return this . tasksRepo . save ( newTask ) ;
}