如何解决Prisma:查询子关系的最有效方式
我有2个解决方案,并且都在工作。但是哪个更好?还是有更好的解决方案?
- 前端:React + ApolloClient
- 后端:Primsa2 + Graphql Nexus
原始模式:
model Post {
id String @id @default(cuid())
likes Like[]
}
model Like {
id String @id @default(cuid())
post Post? @relation(fields: [postId],references: [id])
postId String?
user User @relation(fields: [userId],references: [id])
userId String
}
model User {
id String @id @default(cuid())
likes Like[]
}
两种解决方案的queryField都相同:
export const posts = queryField('posts',{
type: 'Post',list: true,resolve: async (_parent,args: any,{ prisma,request },info) => {
opArgs={
//unimportant
}
return prisma.post.findMany(opArgs)
},})
前端:ApolloClient
const POSTS_USER = gql`
query posts(
$currentUserId: String
) {
posts {
id
likes(where: { user: { id: { equals: $currentUserId } } }) { // where condition!
id
}
}
}
`;
const POSTS_NO_USER = gql`
query posts(
$currentUserId: String
) {
posts {
id
}
}
`;
const { data,loading } = useQuery(user? POSTS_USER: POSTS_NO_USER,{
variables: {
currentUserId: user ? user.id : "",},});
后端Nexus对象:
const Post = objectType({
name: 'Post',deFinition(t) {
t.model.id()
t.model.likes({
filtering: {
user: true,})
},})
前端:ApolloClient
const POSTS = gql`
query posts {
posts {
id
likes { // NO where condition!
id
}
}
}
`;
const { data,loading } = useQuery(POSTS);
使用Nexus后端:
const Post = objectType({
name: 'Post',deFinition(t) {
t.model.id()
t.model.likes()
t.list.field('likes',{
type: 'Like',resolve: (parent,args,request }) => {
const user = getUser(request,false)
if (!user) {
return []
} else {
return prisma.like.findMany({
where: {
postId: parent.id,userId: user.id,})
}
},})
解决方法
第一种方法为什么更好?
当您进行第一个查询时,prisma将在1个DB查询中进行查询。 当您进行第二次查询时,您将拥有数据库查询,因为您拥有职位编号
使用我的PrismaSelect插件的最佳方法Prisma Select在一般graphql参数(父,arg,上下文,信息)中使用info: GraphQLResolveInfo
对象来选择prisma client
接受的对象。该方法可提供更好的性能,因为您将只使用一个解析器来检索所有请求。这样,还可以消除N + 1
问题。
但是您还需要使用nexus-plugin-prisma删除并使用我的pal.js CLI自动生成CRUD
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。