创建新类型,由两种类型组合而成?

huangapple go评论93阅读模式
英文:

Graphql create new type from two types?

问题

我正在尝试为数据库中的表设置一些类型,一个是city,另一个是vendor。当我在这些表上进行连接时,我会得到它们的返回,所以我想我可以做一个union CityVendor = City | Vendor,并将其作为nearby_vendors的返回类型。类型看起来是这样的:

英文:

I am trying to setup some types for tables in a database, one for city and one for vendor. When I do a join on the tables I get them both back, so I thought that I could do a union CityVendor = City | Vendor and say that is the return type for the nearby_vendors. The types look like this:

  type City {
    zip: String
    zone: String
    city: String
    state: String
    latitude: Float
    longitude: Float
    distance: Float
  }

  type Vendor {
    vendor_id: Int
    zip: String
    name: String
    address: String
    avatar: String
    description: String
    private: Boolean
  }

  union CityVendor = City | Vendor

  type Query {
    nearby_vendors(longitude: Float!, latitude: Float!, distance: Int): [CityVendor]
  }

However, when executed, I get this error:

> Cannot query field "name" on type "CityVendor". Did you mean to use an inline fragment on "Vendor"?

Is there a way I can combine two types in graphql to make a single type so that this works?

答案1

得分: 1

你需要按照它所说的使用内联片段编写代码。你可能需要修改传入的变量,我看不到完整的上下文,但它需要看起来像这样:

query Foo($bar: String) {
  nearby_vendors(bar: $bar) {
    # 这些字段存在于 City  Vendor 
    zip

    ... on City {
      # 仅在 City 上存在这些字段
      longitude
    }

    ... on Vendor {
      # 仅在 Vendor 上存在
      avatar
    }
  }
}
英文:

You need to write it with inline fragments as it says. You may need to modify the variables you pass in, I can't see the whole context but it needs to look something like this:

query Foo($bar: String) {
  nearby_vendors(bar: $bar) {
    # these fields exist in both City and Vendor
    zip

    ... on City {
      # only these fields exist on City
      longitude
    }

    ... on Vendor {
      # only exists on Vendor
      avatar
    }
}

huangapple
  • 本文由 发表于 2023年5月21日 03:54:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定