CodingNic

Associations and Relationships

Exercises

Associations and Relationships 30 min read

Exercises

Objectives

By the end of this lesson, you should be able to:

  • Model both a one-to-many and a many-to-many relationship in the same schema
  • Create related records using both create and connect
  • Load related data efficiently with include and select

⚠️ A note on verification: as throughout this module, the Prisma CLI can’t run inside this course’s own sandboxed tooling, so the expected output below reflects Prisma’s stable, documented behavior rather than this course’s own live execution. Run every step yourself, on your own machine, against a real database.

Exercise: A Blog Schema

a) Model the relationships. In a Prisma schema, add:

text
model Author {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

model Post {
  id       Int     @id @default(autoincrement())
  title    String
  author   Author  @relation(fields: [authorId], references: [id])
  authorId Int
  tags     Tag[]
}

model Tag {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

Identify which relationship is one-to-many (Author to Post) and which is many-to-many (Post to Tag), and explain how the schema itself signals the difference (hint: look for a foreign key field).

b) Migrate it. Run prisma migrate dev --name add_blog, and read the generated migration, confirming a join table was created for Post and Tag, and a foreign key column for Post and Author.

c) Create an author with posts. Using create, make one Author with two Posts in a single call.

d) Create and connect tags. Create two Tags ("backend", "tutorial"), then create a new Post connecting both existing tags with connect.

e) Load a post with everything. Fetch a single post with its author and its tags both included in one query.

f) Select a lean shape. Fetch every post as just { title, author: { name } }, using select, no id, no authorId, no full tag objects.

g) Explain the N+1 problem. In your own words, describe what would happen if you fetched all posts, then looped over them fetching each author separately, and explain exactly what include avoids.

Recap

This module covered both relationship shapes a real schema needs: one-to-many with a foreign key field, many-to-many with an implicit join table, and loading related data efficiently with include and select instead of a query per relation.

Next module: the full CRUD query API, findMany, create, update, delete, and filtering, replacing the raw SQL from Modules 1 and 2 with Prisma Client.