Payment

The Payment resource will be pretty simple. This time, choose no to CRUD entry points.

nest g res domain/payments

In payment.entity, define the attributes.

id: number;
registryDates: RegistryDates;

Also associate the ORM decorators, and register it inside the TypeOrmModule.

An order may or may not have a payment, and a payment always belongs to an order. So we can declare a one-to-one relationship, starting on the order's side.

@OneToOne(() => Payment, (payment) => payment.order, { cascade: true })
payment: Payment;

The cascade option allows for saving both an order and its respective payment in a single operation.

We can now do the same on the payment's side.

@OneToOne(() => Order, (order) => order.payment, {
  nullable: false,
  onDelete: 'CASCADE',
})
@JoinColumn()
order: Order;

Some things to note

  • nullable: false forces a payment to always be related to an order

  • onDelete: 'CASCADE' makes that an order deletion also deletes its payment

  • @JoinColumn() is necessary in a one-to-one relationship to indicate, at a database level, which side is the owner side. That is, which side has a reference to the other. As a payment is dependent on an order, it is the better candidate.

Let's finish by generating and running the migration create-payment.

Commit - Creating payment entity and handling one to one relation

Last updated