【问题标题】:Prisma data modeling has many and belongs toPrisma 数据建模有很多和属于
【发布时间】:2019-05-16 20:00:04
【问题描述】:

我有一个包含根类别和子类别的 prisma 数据模型。一个类别有许多子类别,一个子类别属于一个类别。我的模型如下所示:

  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
        }
    }
}

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

【问题讨论】:

    标签: graphql prisma plumatic-schema


    【解决方案1】:

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

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

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

    在这里,我们在 Post 和 User 之间建立了一种模棱两可的关系。 Prisma 需要知道哪个用户字段 (postsWritten?postsLiked?) 链接到哪个帖子字段 (author?likes?)

    为了解决这个问题,我们使用@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 感到困惑。这就解释了为什么您可以查询一种方式而不是另一种方式。

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2019-02-14
    相关资源
    最近更新 更多