ORM
Example
const users = await db.user.findMany();
for (const user of users) {
user.posts = await db.post.findMany({ where: { authorId: user.id } });
}const users = await db.user.findMany({
include: { posts: true },
});Loading the relation with the users avoids the N+1 problem of one extra query per user.
Common mistakes
- Querying inside a loop, causing the N+1 problem with hundreds of small queries.
- Loading whole tables into memory and filtering in code instead of in the query.
Key points
- Related records are loaded with eager loading or a join, not a query inside a loop.
- Raw SQL through the ORM uses parameter binding, not string interpolation.
- Schema changes go through migrations, not automatic schema sync in production.
Interview questions
Do ORMs prevent SQL injection?
Queries the ORM builds are parameterized, so they are safe. Raw queries built with string interpolation are still vulnerable.
ORM vs query builder: what's the difference?
A query builder helps you write SQL in code but returns plain rows. An ORM also maps rows to objects and manages relations.