Product
We'll now create the Product
resource, which will have relations 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
whereverid
is being usedRemove the number conversion operator (
+
) below each occurrenceUse
PaginationDto
in thefindAll()
method (and also in the service)Default page size - 20
Add to the entity the ORM decorators (
@Entity()
,@Column()
, etc)Define
name
asunique
Define
description
asnullable
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