英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论