graphql - 嵌套查询 - Graphql
问题描述
我有一个不返回嵌套对象的 typeDefs
我想在嵌套查询中查询具有所有者和文档的公寓,但它返回 null。
该文件引用了相应的数据文件。
const apartments = require('./data/apartment.json');
const person = require('./data/person.json');
const document = require('./data/document.json');
公寓查询正确返回,但嵌套信息(所有者和相应文档)返回 null
query {
apartments{
id
code
owner{
id
name
document{
name
type
}
}
}
const typeDefs = gql`
type Query {
apartments(
id:ID
code: String
description: String
createdAt: String
updatedAt: String
): [Apartment]
person:[Person]
}
type Apartment {
id: ID
code: String
description: String
owner:[Person]
createdAt: String
updatedAt: String
}
type Person {
id: ID
name: String
document: [Document]
createdAt: String
updatedAt: String
}
type Document {
id: ID
name: String
type: String
number: String
createdAt: String
updatedAt: String
}
`
这是解析器
const resolvers = {
Query: {
apartments: () => {
return apartments;
},
person: () => {
return person;
},
document: () => {
return document;
}
}
}
任何人都可以帮助检索嵌套数据吗?
解决方案
我错过了解析器,所以我将字段更新为人员并更新了解析器
people(parent) {
return people.filter(person => person.apartmentId === parent.apartmentId);
}
这是新架构
// Schema definition
const typeDefs = gql`
# A Block has a blockName and Apartments
type Block {
blockName: String!
blockCode: String!
apartments: [Apartment!]
}
# A Apartment has a apartmentId and people
type Apartment {
apartmentId: String!
people: [Person!]
}
# People has a name
type Person {
personName: String!
}
# Queries can fetch a list of libraries
type Query {
blocks: [Block]
}
`;
现在解析器映射如下所示:
// Resolver map
const resolvers = {
Query: {
blocks() {
// Return our hardcoded array of blocks
return blocks;
}
},
Block: {
apartments(parent) {
// Filter the hardcoded array of blocks to only include the respective apartment in the blockName
return apartments.filter(apartment => apartment.blockName === parent.blockName);
}
},
Apartment: {
// filter all the people that live at the same apartment
people(parent) {
return people.filter(person => person.apartmentId === parent.apartmentId);
}
}
};
嵌套查询看起来像这样
query GetPeopleByBlockAndApartment {
blocks {
blockCode
blockName
apartments {
apartmentId
people {
personName
}
}
}
}
非常感谢所有试图提供帮助的人。
推荐阅读
- javascript - 如何汇总表格行中的所有总数?JS
- c# - 使用 O365 Graph Api 创建事件时显示日历请求
- python - AWS SNS 如何订阅 HTTPS 终端节点
- javascript - 如何下载使用 GIF.js 创建的 GIF?
- javascript - 我试图用 JS 构建 pacman,但我得到一个错误,说无法读取未定义的属性
- angular - Angular Ngrx 按钮逻辑
- firebase - Firebase 会在一段时间后删除使用“测试电话号码”创建的经过身份验证的用户吗?
- sql - 将数据插入共享点列表时出现问题
- amazon-web-services - AWS client-s3 getSignedUrl 等效项
- javascript - three.js - 网格上的全局透明度