> For the complete documentation index, see [llms.txt](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/core-module-backend-development-with-nestjs/remaining-domain/entities/order-item.md).

# 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 <mark style="color:blue;">**`OrderItem`**</mark>. It is a **many-to-many** relationship with **custom properties**. We should then create the file <mark style="color:purple;">orders</mark>/<mark style="color:purple;">entities</mark>/<mark style="color:purple;">order-item.entity</mark>. Also register it in the <mark style="color:blue;">`TypeOrmModule`</mark> inside the <mark style="color:blue;">`OrdersModule`</mark>.

Let's begin by declaring its attributes and setting the ORM decorators. Remember that <mark style="color:blue;">`price`</mark> was already explained in the previous lesson.

```typescript
quantity: number;
price: number;
```

Now, let's discuss about this entity's <mark style="color:blue;">`id`</mark>. It will not be a serial id like in 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.

```typescript
@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 <mark style="color:blue;">`cascade`</mark>.

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

{% hint style="info" %} <mark style="color:blue;">`cascade`</mark> allows for saving an order and its items in a single operation.
{% endhint %}

It may make sense to fetch a product with the orders in which it is present, so we'll create a <mark style="color:blue;">`get`</mark> field in <mark style="color:purple;">product.entity</mark> to allow this.

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

Finally, generate and run the migration <mark style="color:orange;">create-order-item</mark>.

<mark style="color:green;">**Commit**</mark> - Creating order item entity and handling many to many relation with custom properties
