首页 > 解决方案 > Graphcool 模型中的嵌套类型

问题描述

我正在尝试将嵌套数据结构添加到Graph.cool中的模型中,但如果我弄清楚如何做,我就无法终生。

本质上,这就是我想要实现的目标:

type Invoice @model {
  id: ID! @isUnique
  user: Int!
  createdAt: DateTime!
  items: [LineItem!]!
}

type LineItem {
  # Product is defined elsewhere and is unrelated to the problem
  product: Product! @relation(name: "InvoiceProduct")!
  amount: Int!
}

上面的代码曾经可以工作(请参阅此 SO 答案以供参考https://stackoverflow.com/a/50784501/641755)但是当我通过命令行工具进行部署时,会出现此错误 $ The model 'LineItem' is missing the @model directive. Please add it. See: https://github.com/graphcool/framework/issues/817……该 github 链接已失效。

但是,我发现了这个https://github.com/prisma/prisma/issues/817。现在所有类型都需要@model。Invoice这意味着一个类型必须有一个 ID,我需要在和之间建立关系LineItem。好吧,这意味着我们最终会:

type Invoice @model {
  id: ID! @isUnique
  createdAt: DateTime!
  user: Int!
  items: [LineItem!]! @relation(name: "InvoiceLineItem")
}

type LineItem @model {
  id: ID! @isUnique
  product: Product! @relation(name: "InvoiceProduct")!
  amount: Int!
  invoice: Invoice! @relation(name: "InvoiceLineItem")
}

现在,由于多种原因,这是一个问题

  1. 如果我的发票包含 50 个行项目,我需要先创建所有这些行项目。我不能只发送 Invoice 突变的请求负载中的行项目部分。
  2. 我在数据库中得到了一个完全没有用的 LineItem 表。

我想要的只是能够发送以下有效负载:

// Invoice
{
  user: 123,
  items: [
    {
      product: "*id*"
      amount: 3
    },
    {
      product: "*id*"
      amount: 5
    }
  ]
}

我可以看到 Graph.cool 有一个Json 类型,所以我想我可以手动JSON.stringify()发票项目并以这种方式存储它们,但这意味着我根本没有对字段进行服务器端验证,我真的不想最终得到该解决方案。

任何想法、建议或提示将不胜感激。

标签: graphqlgraphcool

解决方案


推荐阅读