Sikau

Prisma · Day 7 · about 35 min

Reading related data

include, nested select, _count and relation filters.

Joins without JOIN

A customer page needs the customer, their orders and each order's dishes. With Prisma you shape the answer as an object tree: include adds relations, select picks exactly the fields you want, and some/every/none filter by related rows.

Shaping the result

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const asha = await prisma.customer.findUnique({
  where: { email: "[email protected]" },
  include: {
    orders: {
      where: { status: "served" },
      include: { items: { include: { dish: { select: { name: true, price: true } } } } },
    },
  },
});
console.log(asha);

console.log(await prisma.customer.findMany({
  select: { name: true, _count: { select: { orders: true } } },
  orderBy: { orders: { _count: "desc" } },
}));

console.log(await prisma.dish.findMany({
  where: { orderItems: { some: { qty: { gte: 2 } } } },
  select: { name: true, category: { select: { name: true } } },
}));

Loading relations in a loop (one query per customer) is the N+1 problem. include fetches each level in one query instead.

The rest of this lesson

  • Select for lean responsesexplain
  • Counting and filtering by relationsexplain
  • Which customers?predict
  • Pick the relation filtermatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Prisma