graphql - Prisma数据建模有很多属于

标签 graphql prisma plumatic-schema

我有一个由根类别和子类别组成的棱镜数据模型。一个类别有许多子类别,一个子类别属于一个类别。我的模型如下所示:

  type Category {
    id: ID! @unique
    createdAt: DateTime!
    updatedAt: DateTime!
    name: String!
    subCategories: [SubCategory!]! @relation(name: "Subcategories")
  }

  type SubCategory {
    id: ID! @unique
    createdAt: DateTime!
    updatedAt: DateTime!
    name: String!
    category: Category! @relation(name: "ParentCategory")

    cards: [Card!]! @relation(name: "SubCategoryCards") #Category @relation(name: "CardCategory")
  }

现在,当我去创建一个新的子类别并通过

mutation {
    createSubCategory(data:{
        name:"This is a test"
        category:{
            connect:{
                id:"cjp4tyy8z01a6093756xxb04i"
            }
        }
    }){
        id
        category{
            name
            id
        }
    }
}

这似乎工作正常。下面我查询了子类别及其父类别,并得到了我期望的结果。

{
    subCategories{
        id
        name
        category{
            id
            name
        }
    }
}

但是,当我尝试查询一个类别并获取它的所有子类别时,我得到一个空数组:

{
    categories{
        id
        name
        subCategories{
            id
            name
        }
    }
}

如何查询所有类别并获取其子类别?

最佳答案

根据 the documentation , @relation 指令用于指定关系的两端

让我们采用以下数据模型:

type User {
  postsWritten: [Post!]!
  postsLiked: [Post!]!
}

type Post {
  author: User!
  likes: [User!]!
}

在这里,我们在 Post 和 User 之间有一个模糊的关系。 Prisma 需要知道哪个用户字段(postsWrittenpostsLiked?)链接到哪个 Post 字段(authorlikes) >?)

为了解决这个问题,我们使用 @relation,其名称在关系的两端中使用。

这将使数据模型看起来像这样:

type User {
  postsWritten: [Post!]! @relation(name: "AuthorPosts")
  postsLiked: [Post!]! @relation(name: "UserLikes")
}

type Post {
  author: User! @relation(name: "AuthorPosts")
  likes: [User!]! @relation(name: "UserLikes")
}

因为我们对 postsWrittenauthor 字段使用了相同的名称,所以 Prisma 现在可以在数据库中链接这两个字段。 postsLikedlikes 也是如此。

总之,您的数据模型的问题在于您在关系中使用了不同的名称。这让 Prisma 感到困惑,认为它们是不同的关系。这解释了为什么您可以通过一种方式查询而不是另一种方式。

关于graphql - Prisma数据建模有很多属于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798509/

相关文章:

node.js - prisma 容器中的 AWS ECS 错误 - 环境变量 PRISMA_CONFIG

clojure - 要在Prismatic/Schema中打开/关闭验证的全局标志?

clojure - 为什么使用 onyx 的棱柱模式验证失败(ExceptionInfo 值与模式不匹配)?

clojure - 使用 Plumatic Sc​​hema 强制转换为 bigdec

postgresql - 如何在 Prisma 中播种关系

graphql - 如何在graphql突变中设置多对多关系?

GraphQL - 有条件地执行子查询

javascript - GraphQL:在文件上传期间解决 promise 时出错

graphql - 我是否应该在 graphql 模式文件中将每个对象写为 'input' 和 'type' 两次

postgresql - Prisma模型自引用(一对多)