Product

We'll now create the Product resource, which will have relation with category and order.

nest g res domain/products

Define the entity's attributes.

id: number;
name: string;
description: string;
price: number;
registryDates: RegistryDates;

Then, execute the necessary steps to finish assembling the new resource

  • In the controller, use the IdDto wherever id is being used

  • Remove the number conversion operator (+) below each occurrence

  • Use PaginationDto in the findAll() method (and also in the service)

    • Default page size - 20

  • Add to the entity the ORM decorators (@Entity(), @Column(), etc)

    • Define name as unique

    • Define description as nullable

  • Register the entity inside the TypeOrmModule in the resource's own module

To have a price with two decimal places, use the following options. In this case, the total number of digits is also necessary.

{ type: 'decimal', precision: 6, scale: 2 }

A category can have many products, and a product can belong to many categories. We can see that this is a many-to-many relationship. In category.entity, we should have

@ManyToMany(() => Product, (product) => product.categories)
products: Product[];

And in product.entity, we use @JoinTable(), representing the association table. We also define the name property because the default name is not so interesting.

@ManyToMany(() => Category, (category) => category.products)
@JoinTable({ name: 'product_to_category' })
categories: Category[];

Generate and run the migration create-product and we can proceed.

Commit - Creating product entity and handling many to many relation

Last updated