Order Item

Finally, we must create a relation between product and order, which will require the emergence of an intermediate entity to carry extra properties of this relation, the entity OrderItem. It is a many-to-many relationship with custom properties. We should then create the file orders -> entities -> order-item.entity.

Let's begin by declaring its attributes and setting the ORM decorators. Remember that price was already explained in the previous lesson.

quantity: number;
price: number;

Now, let's discuss about this entity's id. It will not have a serial id like the other entities. This is because what uniquely identifies an order item is the order to which it belongs and the product that represents its type. Because of that, at the top of the class, we'll insert the two entities that have a relationship with it and also both their ids as this entity's own id.

@PrimaryColumn()
orderId: number;

@PrimaryColumn()
productId: number;

@ManyToOne(() => Order, (order) => order.items, { onDelete: 'CASCADE' })
order: Order;

@ManyToOne(() => Product, (product) => product.items)
product: Product;

Finally, define the relation at the side of order and product. The following code is for the order side, the product side is similar but without the cascade.

@OneToMany(() => OrderItem, (item) => item.order, { cascade: true })
items: OrderItem[];

cascade allows for saving an order and its items in a single operation.

It may make sense to fetch a product with the orders in which it is present, so we'll create a get field in product.entity to allow this.

get orders() {
  return this.items.map((item) => item.order);
}

Finally, generate and run the migration create-order-item.

Commit - Creating order item entity and handling many to many relation with custom properties

Last updated