文档
演练
关系

关系

示例使用以下 prisma 模式

model User {
  id    String @id @default(cuid())
  name  String
  posts Post[]
}
 
model Post {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  published Boolean
  title     String
  content   String?
 
  // optional author
  user   User?   @relation(fields: [userID], references: [id])
  userID String?
 
  comments Comment[]
}
 
model Comment {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now())
  content   String
 
  post   Post   @relation(fields: [postID], references: [id])
  postID String
}

通过嵌套关系查找

在查询中,您可以使用“Some”、“Every”或“None”来查询关系。

查看“Every”过滤器的注意事项 (在新标签页中打开)

// get posts which have at least one comment with a content "My Content" and that post's titles are all "What up?"
posts, err := client.Post.FindMany(
  db.Post.Title.Equals("What up?"),
  db.Post.Comments.Some(
    db.Comment.Content.Equals("My Content"),
  ),
).Exec(ctx)

您可以根据需要嵌套关系查询。

users, err := client.User.FindMany(
  db.User.Name.Equals("Author"),
  db.User.Posts.Some(
    db.Post.Title.Equals("What up?"),
    db.Post.Comments.Some(
      db.Comment.Content.Equals("My Content"),
    ),
    db.Post.Comments.None(
      db.Comment.Content.Equals("missing"),
    ),
  ),
).Exec(ctx)