We use Prisma to set up our database relations, as well as handle any querying. Make sure to download the Prisma VS Code extension.

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  name      String?
  role      Role     @default(USER)
  posts     Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  published Boolean  @default(false)
  title     String   @db.VarChar(255)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

enum Role {
  USER
  ADMIN
}

The above file will generate a database schema with tables Post and User. It will also generate any necessary TypeScript definitions to make fully type-hinted queries.

A nice part about the Prisma generator is it can automatically define relations for you. For example, if you type out one side of a relationship, after formatting the file, the extension automatically can automatically define the other. For example

// Before Formatting
model User {
  id   String @id @default(cuid())
  name String
  posts Post[] // one sided relationship
}

model Post {
  id String @id @default(cuid())
}

// After Formatting
model User {
  id    String @id @default(cuid())
  name  String
  posts Post[]
}

model Post {
  id     String  @id @default(cuid())
  User   User?   @relation(fields: [userId], references: [id])
  userId String?
}

Prisma Client

Prisma client is what lets us query the database.

Once we have set up our models, we can then use client to query this database with full type hinting:

const user = await prisma.user.create({
  data: {
    email: '[email protected]',
    name: 'User Test',
  },
})