簡體   English   中英

Graphql 查詢:如何創建返回項目之間不同字段的查詢

[英]Graphql query: how to create a query that returns different fields between items

我的查詢是在數據庫中找到一家公司,返回一些基本信息,以及歷年的財務信息。 結果如下:

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

有什么辦法可以讓查詢達到這樣的結果?

不,沒有辦法編寫這樣的查詢。

特定列表中返回的所有項目將具有相同的選擇集。 唯一的例外是當您請求具有聯合或接口類型的字段時——然后您可以使用內聯片段為每種可能的類型指定一個選擇集。

正如評論中已經建議的那樣,唯一可能的解決方法是使用別名。 假設您的架構允許您按年份過濾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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM