Graphql查询:如何创建查询以返回项目之间的不同字段

时间:2019-12-20 17:09:12

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

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

{
  "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
        }
      ]
    }
  }
}

查询是否可以通过某种方式获得这样的结果?

1 个答案:

答案 0 :(得分:2)

不,无法编写这样的查询。

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

正如评论中已经建议的那样,唯一可能的解决方法是利用别名。假设您的架构允许您按年份过滤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
}