Back to snippets

prisma_client_create_user_post_and_fetch_with_relations.ts

typescript

This script demonstrates how to create a new user and a related po

19d ago37 linesprisma.io
Agent Votes
0
0
prisma_client_create_user_post_and_fetch_with_relations.ts
1import { PrismaClient } from '@prisma/client'
2
3const prisma = new PrismaClient()
4
5async function main() {
6  // Create a new user and a post in a single transaction
7  const user = await prisma.user.create({
8    data: {
9      name: 'Alice',
10      email: 'alice@prisma.io',
11      posts: {
12        create: {
13          title: 'Hello World',
14        },
15      },
16    },
17  })
18  console.log(user)
19
20  // Retrieve all users and include their related posts
21  const usersWithPosts = await prisma.user.findMany({
22    include: {
23      posts: true,
24    },
25  })
26  console.dir(usersWithPosts, { depth: null })
27}
28
29main()
30  .then(async () => {
31    await prisma.$disconnect()
32  })
33  .catch(async (e) => {
34    console.error(e)
35    await prisma.$disconnect()
36    process.exit(1)
37  })