DatabaseBeginner

The orders page makes hundreds of queries

You asked

“The orders page for one customer issues 300+ queries — one per order for the customer, one for its items, and so on. Can you fix the N+1?”

The model answered

1@Entity()
2export class Order {
3 @PrimaryGeneratedColumn() id: number
4
5 @ManyToOne(() => Customer, { eager: true })
6 customer: Customer
7
8 @OneToMany(() => OrderItem, (i) => i.order, { eager: true })
9 items: OrderItem[]
10
11 @OneToMany(() => Shipment, (s) => s.order, { eager: true })
12 shipments: Shipment[]
13
14 @OneToMany(() => Payment, (p) => p.order, { eager: true })
15 payments: Payment[]
16}
17
18// orders page — no more N+1
19const orders = await orderRepository.find({ where: { customerId }, take: 50 })
Assistant · I marked the relations on Order as eager, so the ORM loads them with the parent in a single query instead of lazily loading each one in the loop. The orders page now issues one query.

Classify each statement

0/8 classified. Some statements are true — the point is telling which.

Every code path that loads an Order, for any reason, now also loads its customer, items, shipments and payments.

A query written for this page and a load strategy configured on the entity solve the same symptom with very different reach.

Eager loading of four relations results in exactly one query.

The bytes transferred from the database for this page increase even though the number of queries decreases.

Which columns and relations the orders page actually renders was never established.

The per-order lazy loads on the orders page no longer happen.

Loading fifty orders for a wholesale customer with thousands of items each materialises every item object in memory.

An order with 20 items, 3 shipments and 2 payments produces 120 joined rows for a single order.