Product
We'll now create the Product resource, which will have relations with category and order.
nest g res domain/productsDefine 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
IdDtowhereveridis being usedRemove the number conversion operator (
+) below each occurrenceUse
PaginationDtoin thefindAll()method (and also in the service)Default page size - 20
Add to the entity the ORM decorators (
@Entity(),@Column(), etc)Define
nameasuniqueDefine
descriptionasnullable
Register the entity inside the
TypeOrmModulein 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