Change Datamodel
Goals
On this page, you will learn how to:
- Adjust the datamodel and update your Prisma API
- Regenerate your Prisma client
- Create two database records in a single transaction
- Query relational data
This page is only relevant if you started with a new database or a demo server. If you configured Prisma with an existing database, you need to run migrations directly against your database.
Adjust your datamodel
Update the datamodel in datamodel.prisma
as follows:
type User { id: ID! @unique email: String @unique name: String! posts: [Post!]! } type Post { id: ID! @unique title: String! published: Boolean! @default(value: "false") author: User }
Copy
Here's what changed:
- You added a new
email
field to theUser
type. - You added a new
Post
type to the datamodel. - You added a relation between
User
andPost
(via theposts
andauthor
fields).
Redeploy your Prisma API
To apply the changes you just made to your datamodel, you need to redeploy the Prisma API:
prisma deploy
Copy
Regenerate your Prisma client
Because the Prisma client is based on your datamodel, it needs to be regenerated every time the datamodel is updated:
prisma generate
Copy
The Prisma client library in the /generated/prisma-client
directory is now being updated and its API has been adjusted to use the new datamodel.
Read and write nested objects
The Prisma client API allows to write nested objects in a single transaction without having to manually control when the transaction starts or ends.
Update your index.ts
to look as follows:
import { prisma } from './generated/prisma-client' // A `main` function so that we can use async/await async function main() { // Create a new user with a new post const newUser = await prisma.createUser({ name: 'Bob', email: 'bob@prisma.io', posts: { create: { title: 'The data layer for modern apps', }, }, }) console.log(`Created new user: ${newUser.name} (ID: ${newUser.id})`) // Read all users from the database and print them to the console const allUsers = await prisma.users() console.log(allUsers) const allPosts = await prisma.posts() console.log(allPosts) } main().catch(e => console.error(e))
Copy
Run the script with the following command:
npm run start
Copy
Query relational data
With the Prisma client API, you can navigate relations in your data graph using chained method calls (also called fluent API). Here is how you can query the posts
written by a certain User
:
import { prisma } from './generated/prisma-client' // A `main` function so that we can use async/await async function main() { // Read the previously created user from the database and print their posts to the console const postsByUser = await prisma.user({ email: 'bob@prisma.io' }).posts() console.log(`All posts by that user: ${JSON.stringify(postsByUser)}`) } main().catch(e => console.error(e))
Copy