Relaciones y consultas avanzadas con Prisma
Modele relaciones uno a muchos y muchos a muchos, y después consulte a través de ellas con escrituras anidadas, include, select, filtrado y paginación.
Relaciones y consultas avanzadas con Prisma es una lección gratuita de Next.js 15 Fullstack Web Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack Web Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Relations?
Real data is connected: a user has many posts, a post has many tags. Prisma models these relations in the schema so you can traverse them in type-safe queries.
One-to-Many in the Schema
A one-to-many relation links a parent to many children via a foreign key. Define both sides in the schema.
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
authorId Int
author User @relation(fields: [authorId], references: [id])
}Many-to-Many
Prisma supports implicit many-to-many with just array fields on both sides; it manages the join table for you.
model Post { id Int @id @default(autoincrement()) tags Tag[] }
model Tag { id Int @id @default(autoincrement()) posts Post[] }Including Related Data
By default queries return only the model fields. Use include to fetch related records too.
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true },
});Selecting Specific Fields
Use select to fetch only the columns you need — leaner payloads and faster queries. You can nest select for relations.
const posts = await prisma.post.findMany({
select: { id: true, title: true, author: { select: { name: true } } },
});Nested Writes
Create a parent and its children in one call with a nested create. Prisma runs it in a transaction.
await prisma.user.create({
data: {
name: 'Ada',
posts: { create: [{ title: 'Hello' }, { title: 'World' }] },
},
});Filtering with where
Build rich filters with operators like contains, gt, in, and combine them with AND/OR.
const recent = await prisma.post.findMany({
where: {
published: true,
title: { contains: 'Prisma' },
},
});Filtering on Relations
You can filter a parent by a condition on its children using some, every, or none.
const authors = await prisma.user.findMany({
where: { posts: { some: { published: true } } },
});Sorting and Pagination
Order results with orderBy and page with take/skip (offset) for classic pagination.
const page = await prisma.post.findMany({
orderBy: { createdAt: 'desc' },
take: 10,
skip: 20,
});Cursor Pagination
For large or live datasets, cursor-based pagination is more stable than offset. Pass the last seen id as a cursor.
const next = await prisma.post.findMany({
take: 10,
cursor: { id: lastId },
skip: 1,
});Avoiding N+1 Queries
Fetching a list and then querying each item separately causes the N+1 problem. Prisma avoids it: use a single include to load relations in one optimized query rather than looping.
Quick Check
Test your Prisma relations knowledge.
Recap
You learned relational querying with Prisma:
- Model one-to-many and many-to-many relations in the schema
- Fetch relations with
include; trim fields withselect - Nested writes create parents and children atomically
- Filter on relations, paginate with take/skip or cursors, and avoid the N+1 problem
Preguntas frecuentes
¿La lección «Relaciones y consultas avanzadas con Prisma» es gratis?
Sí — el texto completo de «Relaciones y consultas avanzadas con Prisma» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack Web Apps, actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Relaciones y consultas avanzadas con Prisma»?
Modele relaciones uno a muchos y muchos a muchos, y después consulte a través de ellas con escrituras anidadas, include, select, filtrado y paginación. Practicas Next.js 15 Fullstack Web Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Next.js 15 Fullstack Web Apps?
No se requiere experiencia previa. Next.js 15 Fullstack Web Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Relaciones y consultas avanzadas con Prisma»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack Web Apps?
Sí. Cada lección de Next.js 15 Fullstack Web Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción al ORM Prisma
- Diseño de esquemas y migraciones con Prisma
- Operaciones CRUD con Prisma Client
- Relaciones y consultas avanzadas con Prisma