我在学习GraphQL
所以我建立了一个小项目。假设我有 2 个模型,User
and Comment
.
const Comment = Model.define('Comment', {
content: {
type: DataType.TEXT,
allowNull: false,
validate: {
notEmpty: true,
},
},
});
const User = Model.define('User', {
name: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
phone: DataType.STRING,
picture: DataType.STRING,
});
关系是one-to-many
,其中用户可以有很多评论。
我已经构建了这样的架构:
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: {
type: GraphQLString
},
name: {
type: GraphQLString
},
phone: {
type: GraphQLString
},
comments: {
type: new GraphQLList(CommentType),
resolve: user => user.getComments()
}
})
});
和查询:
const user = {
type: UserType,
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(_, {id}) => User.findById(id)
};
对用户及其评论执行查询是通过 1 个请求完成的,如下所示:
{
User(id:"1"){
Comments{
content
}
}
}
据我了解,客户端将使用 1 个查询获得结果,这是使用的好处GraphQL
。但服务器将执行 2 个查询,一个针对用户,另一个针对他的评论。
我的问题是,构建GraphQL
架构和类型以及表之间的联接,以便服务器也可以通过 1 个请求执行查询?