Apuntes
category.entity
// src\products\entities\category.entity.ts
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'varchar', length: 255, unique: true})
name: string;
@CreateDateColumn({
type: 'timestamptz',
default: ()=> 'CURRENT_TIMESTAMP'
})
createAt: Date;
@UpdateDateColumn({
type: 'timestamptz',
default: ()=> 'CURRENT_TIMESTAMP'
})
updateAt: Date;
}
category.service
// src\products\services\categories.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Category } from '../entities/category.entity';
import { CreateCategoryDto, UpdateCategoryDto } from '../dtos/category.dtos';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { merge } from 'rxjs';
@Injectable()
export class CategoriesService {
constructor(
@InjectRepository(Category) private categoryRepo: Repository<Category>
){}
findAll() {
return this.categoryRepo.find();
}
async findOne(id: number) {
const category = await this.categoryRepo.findOne(id);
if (!category) {
throw new NotFoundException(`Category #${id} not found`);
}
return category;
}
create(data: CreateCategoryDto) {
const newCategory = this.categoryRepo.create(data);
return this.categoryRepo.save(newCategory);
}
async update(id: number, changes: UpdateCategoryDto) {
const category = await this.findOne(id);
this.categoryRepo.merge(category, changes);
return this.categoryRepo.save(category);
}
remove(id: number) {
return this.categoryRepo.delete(id);
}
}
products module
// src\products\products.module.ts
@Module({
...
// Agregamos a category
imports:[TypeOrmModule.forFeature([Product, Brand, Category])],
...
})
Creando la relacion
// src\products\entities\category.entity.ts
@ManyToMany(()=>Product, (product)=>product.categories)
@JoinTable() // Solo debe estar en una entidad
products: Product[]
// src\products\entities\product.entity.ts
@ManyToMany(()=>Category, (category)=>category.products)
categories: Category[];
Crear y correr la migracion
npm run migrations:generate -- create-categories
npm run migrations:run
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?