Read related records
A user profile page needs a user's posts or profile data in the same response.
Prisma · Const
include adds specified related records to a Prisma Client query result. The related data is returned nested under each parent record, and nested select can narrow the relation's fields.
Use include in a Prisma Client query to request related records alongside each parent record. The relation fields are returned nested on the parent, and a nested select can limit the fields returned from an included relation.
include: { relationName: true }| Name | Type | Description |
|---|---|---|
include | Prisma relation-selection object | An object whose keys are relation field names and whose values configure whether and how those relations are returned. |
The queried records with the requested related records nested under their relation field names.
true inside include to return that related data with each parent record.select, allowing the query to return only selected fields from that related model.include or select can choose a relation loading strategy at the outermost query level.select when you need a narrower shape.const users = await prisma.user.findMany({
where: { role: "ADMIN" },
include: { posts: true },
});Fetches administrator users together with their related posts.
A user profile page needs a user's posts or profile data in the same response.
An API should return a relation but omit unnecessary columns from it.
A query needs to compare database-level and application-level relation loading.
include option do?include defines which relations Prisma Client includes in the returned result. It is used for nested reads, such as returning a user's posts or profile with the user.
Follow-up: How would you reduce the included relation's payload? Use a nested select inside include to choose particular related fields.
include change it?By default, Prisma Client returns all scalar fields for the queried model but no relations. Adding include requests specified relations and returns them nested under the parent record.
Follow-up: What alternative is available when you need a precisely shaped result? Use select, which can choose scalar fields and relations explicitly.
The relation load strategy can be selected at the top level for queries supporting include or select. join uses a database-level join or correlated subqueries, while query sends multiple queries and combines results in the application.
Follow-up: When might query be preferable? It can be useful when reducing database-server resource use or when profiling shows application-level joining performs better.
selectrelationLoadStrategyRelation queriesSelect fields