Query Avanzate
Filtering (where)
Filtri di Base
// Uguaglianza
const user = await prisma.user.findMany({
where: { role: 'ADMIN' },
})
// Confronto numerico
const products = await prisma.product.findMany({
where: {
price: { gt: 10 }, // maggiore di
stock: { gte: 1 }, // maggiore o uguale
discount: { lt: 50 }, // minore di
},
})
Filtri su Stringhe
const users = await prisma.user.findMany({
where: {
email: { contains: 'gmail.com' }, // Contiene
name: { startsWith: 'Mar' }, // Inizia con
// name: { endsWith: 'ssi' }, // Finisce con
// email: { contains: 'GMAIL', mode: 'insensitive' }, // Case-insensitive
},
})
Operatori IN e NOT
// IN: il valore deve essere tra quelli elencati
const adminsAndMods = await prisma.user.findMany({
where: {
role: { in: ['ADMIN', 'MODERATOR'] },
},
})
// NOT IN
const regularUsers = await prisma.user.findMany({
where: {
role: { notIn: ['ADMIN', 'MODERATOR'] },
},
})
// NOT: nega la condizione
const nonAdmins = await prisma.user.findMany({
where: {
NOT: { role: 'ADMIN' },
},
})
Operatori Logici (AND, OR, NOT)
const results = await prisma.post.findMany({
where: {
OR: [
{ title: { contains: 'Prisma' } },
{ content: { contains: 'database' } },
],
AND: [
{ published: true },
{ createdAt: { gte: new Date('2025-01-01') } },
],
},
})
Filtrare su Relazioni
// Post di utenti con ruolo ADMIN
const adminPosts = await prisma.post.findMany({
where: {
author: {
role: 'ADMIN',
},
},
})
// Utenti che hanno almeno un post pubblicato
const activeAuthors = await prisma.user.findMany({
where: {
posts: {
some: { published: true },
},
},
})
// Utenti senza post
const inactiveUsers = await prisma.user.findMany({
where: {
posts: {
none: {},
},
},
})
// Utenti dove TUTTI i post sono pubblicati
const fullyPublished = await prisma.user.findMany({
where: {
posts: {
every: { published: true },
},
},
})
Sorting (orderBy)
// Ordinamento singolo
const posts = await prisma.post.findMany({
orderBy: { createdAt: 'desc' },
})
// Ordinamento multiplo
const users = await prisma.user.findMany({
orderBy: [
{ role: 'asc' },
{ name: 'asc' },
],
})
// Ordinare per campo di relazione
const posts2 = await prisma.post.findMany({
orderBy: {
author: { name: 'asc' },
},
})
// Ordinare per conteggio di relazione
const popularUsers = await prisma.user.findMany({
orderBy: {
posts: { _count: 'desc' },
},
})
Pagination
Offset Pagination (skip/take)
const page = 2
const pageSize = 10
const posts = await prisma.post.findMany({
skip: (page - 1) * pageSize, // Salta i primi N risultati
take: pageSize, // Prendi N risultati
orderBy: { createdAt: 'desc' },
})
// Contare il totale per calcolare le pagine
const totalPosts = await prisma.post.count({
where: { published: true },
})
const totalPages = Math.ceil(totalPosts / pageSize)
Cursor Pagination
Piu’ efficiente per dataset grandi:
// Prima pagina
const firstPage = await prisma.post.findMany({
take: 10,
orderBy: { id: 'asc' },
})
// Pagine successive: usa l'ultimo ID come cursore
const lastPost = firstPage[firstPage.length - 1]
const secondPage = await prisma.post.findMany({
take: 10,
skip: 1, // Salta il cursore stesso
cursor: { id: lastPost.id },
orderBy: { id: 'asc' },
})
Select e Include
select
Seleziona solo campi specifici (riduce i dati trasferiti):
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
// role, createdAt, ecc. NON vengono restituiti
},
})
include
Include relazioni nel risultato:
const users = await prisma.user.findMany({
include: {
posts: true, // Tutti i post
profile: true, // Profilo
_count: { select: { posts: true } }, // Solo il conteggio
},
})
Combinare select con relazioni
const users = await prisma.user.findMany({
select: {
name: true,
posts: {
select: { title: true, published: true },
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5,
},
},
})
Nota: select e include non possono essere usati insieme nello stesso livello.
Distinct
Restituisce solo valori univoci per campi specifici:
// Citta' univoche degli utenti
const cities = await prisma.user.findMany({
distinct: ['city'],
select: { city: true },
})
// Combinazioni uniche di citta' e ruolo
const uniqueCombos = await prisma.user.findMany({
distinct: ['city', 'role'],
select: { city: true, role: true },
})