A煤n no tienes acceso a esta clase

Crea una cuenta y contin煤a viendo este curso

Relaciones muchos a muchos

22/33
Recursos

Aportes 3

Preguntas 1

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesi贸n.

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

Tal vez les sirva para nombrar las columnas de las relaciones.

@JoinColumn

Defines which side of the relation contains the join column with a foreign key and allows you to customize the join column name and referenced column name. Example:

@Entity()
export class Post {

@ManyToOne(type => Category)
@JoinColumn({
    name: "cat_id",
    referencedColumnName: "name"
})
category: Category;

}

@JoinTable

Used for many-to-many relations and describes join columns of the 鈥渏unction鈥 table. Junction table is a special, separate table created automatically by TypeORM with columns referenced to the related entities. You can change the name of the generated 鈥渏unction鈥 table and also the column names inside the junction table and their referenced columns with the joinColumn- and inverseJoinColumn attributes. Example:

@Entity()
export class Post {

@ManyToMany(type => Category)
@JoinTable({
    name: "question_categories",
    joinColumn: {
        name: "question",
        referencedColumnName: "id"
    },
    inverseJoinColumn: {
        name: "category",
        referencedColumnName: "id"
    }
})
categories: Category[];

}

Para personalizar los nombres de las tablas y llaves o referencias de la tabla

/user.entity.ts
@OneToOne(() => Customer, (customer) => customer.user, { nullable: true })
  @JoinColumn({
    name: "pk_customer",
    referencedColumnName: "id"
  })
  customer: Customer
/category.entity.ts
@ManyToMany(() => Product, (products) => products.categories, { nullable: true })
  products: Product[];
/product.entity.ts
 @ManyToOne(() => Brand, (brand) => brand.products, { nullable: true })
  brand: Brand

  @ManyToMany(() => Category, (categories) => categories.products, { nullable: true })

  @JoinTable({
    name: "product_categories",
    joinColumn: {
      name: "pk_product",
      referencedColumnName: "id"
    },
    inverseJoinColumn: {
      name: "pk_category",
      referencedColumnName: "id"
    }
  })
  categories: Category[];