【问题标题】:Graphql query: how to create a query that returns different fields between itemsGraphql 查询:如何创建返回项目之间不同字段的查询
【发布时间】:2020-04-13 04:32:59
【问题描述】:

我的查询是在数据库中找到一家公司,返回一些基本信息,以及多年来的财务信息。结果如下:

{
  "data": {
    "company": {
      "id": 1,
      "name": "test company",
      "companyType": "NH",
      "financials": [
        {
          "year": 2018,
          "netRevenue": 0,
          "costOfSales": 0,
          "grossProfit": 0,
          "financialIncome": 0,
          "financialExpenses": 0,
          "resultOfOtherActivities": 0
        },
        {
          "year": 2017,
          "netRevenue": 0,
          "costOfSales": 0,
          "grossProfit": 0,
          "financialIncome": 0,
          "financialExpenses": 0,
          "resultOfOtherActivities": 0
        },
        {
          "year": 2016,
          "netRevenue": 0,
          "costOfSales": 0,
          "grossProfit": 0,
          "financialIncome": 0,
          "financialExpenses": 0,
          "resultOfOtherActivities": 0
        }
      ]
    }
  }
}

编写查询非常简单:

{
  company {
    id
    name
    companyType
    financials {
      year
      netRevenue
      costOfSales
      grossProfit
      financialIncome
      financialExpenses
      resultOfOtherActivities
    }
  }
}

但我的情况并非如此简单。我需要一个查询来检索每年的一些字段。结果如下:

{
  "data": {
    "company": {
      "id": 1,
      "name": "test company",
      "companyType": "NH",
      "financials": [
        {
          "year": 2018,
          "netRevenue": 0
        },
        {
          "year": 2017,
          "grossProfit": 0,
          "financialIncome": 0,
          "financialExpenses": 0
        },
        {
          "year": 2016,
          "resultOfOtherActivities": 0
        }
      ]
    }
  }
}

有没有什么方法可以让查询达到这样的结果?

【问题讨论】:

  • 我不认为你可以做你正在寻找的东西。您可以为有条件需要的字段添加指令 (graphql.org/learn/queries/#directives),但随后您必须针对不同年份分别调用查询,并传入不同的布尔值。
  • @JasonDown 重复查询的成本会很高
  • 是的。但我认为没有其他方法可以做你想做的事。

标签: c# asp.net-core graphql hotchocolate


【解决方案1】:

不,没有办法编写这样的查询。

特定列表中返回的所有项目都将具有相同的选择集。唯一的例外是当您请求具有联合或接口类型的字段时,您可以使用内联片段为每种可能的类型指定选择集。

正如 cmets 中已经建议的那样,唯一可能的解决方法是使用别名。假设您的架构允许您按年过滤 financials 字段,您将执行以下操作:

{
  company {
    id
    name
    companyType
    financials2007: financials(year: 2007) {
      ...FinancialsFields
    }
    financials2008: financials(year: 2008) {
      ...FinancialsFields
    }
    financials2009: financials(year: 2009) {
      ...FinancialsFields
    }
  }
}

fragment FinancialsFields on Financials {
  year
  netRevenue
  costOfSales
  grossProfit
  financialIncome
  financialExpenses
  resultOfOtherActivities
}

【讨论】:

  • 是的,我可以使用别名。非常感谢:D
猜你喜欢
  • 2019-07-08
  • 2022-11-19
  • 2020-07-02
  • 1970-01-01
  • 2018-11-25
  • 2019-07-18
  • 2019-06-14
  • 2020-01-07
  • 2019-11-04
相关资源
最近更新 更多