Prisma makes database relationships intuitive. Here's how to model and query them effectively.
One-to-Many Relationships#
Many-to-Many Relationships#
Self-Relations#
Nested Writes#
Filtering by Relations#
Aggregations with Relations#
Transactions#
Best Practices#
Schema Design:
✓ Use appropriate relation types
✓ Name relations clearly
✓ Consider cascade deletes
✓ Add indexes for foreign keys
Queries:
✓ Use include/select wisely
✓ Avoid N+1 with includes
✓ Filter relations in query
✓ Use transactions for consistency
Performance:
✓ Limit nested includes depth
✓ Paginate relation results
✓ Use count instead of fetching
✓ Index frequently filtered fields
Conclusion#
Prisma makes working with relationships intuitive through its schema definition and query API. Use implicit many-to-many for simple cases and explicit for additional fields. Filter and aggregate through relations efficiently, and use transactions for data consistency across multiple operations.