如何在GraphQL中进行简单的联接? [英] How to do a simple join in GraphQL?
问题描述
我是GraphQL的新手,正在尝试做一个简单的联接查询.我的示例表如下所示:
I am very new in GraphQL and trying to do a simple join query. My sample tables look like below:
{
phones: [
{
id: 1,
brand: 'b1',
model: 'Galaxy S9 Plus',
price: 1000,
},
{
id: 2,
brand: 'b2',
model: 'OnePlus 6',
price: 900,
},
],
brands: [
{
id: 'b1',
name: 'Samsung'
},
{
id: 'b2',
name: 'OnePlus'
}
]
}
我想查询一个返回 phone 对象,其中带有其品牌名称而不是品牌代码.
I would like to have a query to return a phone object with its brand name in it instead of the brand code.
例如如果使用 id = 2
查询电话,它将返回:
E.g. If queried for the phone with id = 2
, it should return:
{id: 2, brand: 'OnePlus', model: 'OnePlus 6', price: 900}
推荐答案
GraphQL作为前端的查询语言,在传统的SQL意义上不支持联接".
GraphQL as a query language on the front-end does not support 'joins' in the classic SQL sense.
相反,它允许您选择要为组件获取的特定模型中的哪些字段.
Rather, it allows you to pick and choose which fields in a particular model you want to fetch for your component.
要查询数据集中的所有电话,您的查询应如下所示:
To query all phones in your dataset, your query would look like this:
query myComponentQuery {
phone {
id
brand
model
price
}
}
您的前端正在查询的GraphQL服务器将具有单独的字段解析器-告诉GraphQL在哪里获取ID,品牌,型号等.
The GraphQL server that your front-end is querying would then have individual field resolvers - telling GraphQL where to fetch id, brand, model etc.
服务器端解析器如下所示:
The server-side resolver would look something like this:
Phone: {
id(root, args, context) {
pg.query('Select * from Phones where name = ?', ['blah']).then(d => {/*doStuff*/})
//OR
fetch(context.upstream_url + '/thing/' + args.id).then(d => {/*doStuff*/})
return {/*the result of either of those calls here*/}
},
price(root, args, context) {
return 9001
},
},
这篇关于如何在GraphQL中进行简单的联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!