高级用法

注意

改编自 Prisma Client Go 文档

快速入门 中,我们创建了一个简单的帖子模型并运行了一些查询。但是,Prisma 和 Python 客户端被设计为与模型之间的关系一起使用。

我们已经创建了一个帖子模型,例如用于博客。假设我们想为帖子添加评论,并将这些模型以一种方式连接起来,以便我们可以依赖 SQL 的外键和 Python 客户端处理关系的能力。

让我们介绍一个新的评论模型,它与帖子模型之间存在一对多关系。

model Post {
  ...
  comments Comment[]
}

model Comment {
  id         String   @default(cuid()) @id
  created_at DateTime @default(now())
  content    String
  post       Post @relation(fields: [post_id], references: [id])
  post_id    String
}
完整的 Prisma Schema
datasource db {
  // could be postgresql or mysql
  provider = "sqlite"
  url      = "file:dev.db"
}

generator db {
  provider             = "prisma-client-py"
  recursive_type_depth = 5
}

model Post {
  id         String    @id @default(cuid())
  created_at DateTime  @default(now())
  updated_at DateTime  @updatedAt
  title      String
  published  Boolean
  desc       String?
  comments   Comment[]
}

model Comment {
  id         String   @id @default(cuid())
  created_at DateTime @default(now())
  content    String
  post       Post     @relation(fields: [post_id], references: [id])
  post_id    String
}

每当你对模型进行更改时,请迁移你的数据库并重新生成你的 prisma 代码。

# apply migrations
prisma migrate dev --name "add comment model"
# generate
prisma generate

为了创建评论,我们可以先创建一个帖子,然后在创建评论时连接该帖子,或者在创建评论时同时创建帖子。

post = await db.post.create({
    'title': 'My new post',
    'published': True,
})
print(f'post: {post.json(indent=2)}\n')

first = await db.comment.create({
    'content': 'First comment',
    'post': {
        'connect': {
            'id': post.id,
        },
    },
})
print(f'first comment: {first.json(indent=2)}\n')

second = await db.comment.create({
    'content': 'Second comment',
    'post': {
        'connect': {
            'id': post.id,
        },
    },
})
print(f'second comment: {second.json(indent=2)}\n')
另一种方法
first = await db.comment.create(
    data={
        'content': 'First comment',
        'post': {
            'create': {
                'title': 'My new post',
                'published': True,
            },
        },
    },
    include={'post': True}
)
second = await db.comment.create({
    'content': 'Second comment',
    'post': {
        'connect': {
            'id': first.post.id
        }
    }
})

现在帖子和评论已经创建好了,你可以按如下方式查询它们。

# find all comments on a post
comments = await db.comment.find_many(
    where={
        'post_id': post.id
    }
)
print(f'comments of post with id {post.id}')
for comment in comments:
    print(comment.json(indent=2))

# find at most 3 comments on a post
filtered = await db.comment.find_many(
    where={
        'post_id': post.id
    },
    take=3
)
print(f'filtered comments of post with id {post.id}')
for comment in filtered:
    print(comment.json(indent=2))

Prisma 还允许你一次获取多个内容。与其进行复杂的联接,你只需几行代码,并保证完全类型安全,就可以获取一个帖子及其部分评论。

# fetch a post and 3 of its comments
post = await db.post.find_unique(
    where={
        'id': post.id,
    },
    include={
        'comments': {
            'take': 3,
        },
    },
)