GraphQL按嵌套字段排序:按用户名称降序获取前10条帖子
按用户名称降序获取前10条帖子的解决方案
好的,咱们来搞定这个需求——按用户name降序获取前10条Posts。结合你给出的Schema定义,我会分两种场景给你解决方案:内存数据映射(适配你现有的userMap)和数据库查询(性能更优)。
场景1:基于内存数据映射(如你的userMap)
首先完善RootQuery,添加topPosts字段来处理排序和筛选逻辑:
var RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { topPosts: { type: new GraphQLList(PostType), resolve() { console.info("RootQuery topPosts resolve called."); // 假设你有postMap存储所有帖子(key为post id,value为帖子对象) const allPosts = Object.values(postMap); // 关联用户信息并按用户名降序排序 const sortedPosts = allPosts .map(post => ({ ...post, // 和你PostType里的resolve逻辑一致,关联用户数据 user: userMap[post.user] })) .sort((postA, postB) => { // 用localeCompare处理字符串排序,支持多语言;忽略大小写可加toLowerCase() return postB.user.name.localeCompare(postA.user.name); }); // 取前10条返回 return sortedPosts.slice(0, 10); } } } });
场景2:基于数据库查询(性能更优,推荐)
如果你的数据存在数据库里(比如MySQL、PostgreSQL),强烈建议在数据库层面完成关联、排序和分页,避免把全量数据加载到内存处理,尤其是数据量大的时候。
比如用SQL直接查询:
SELECT p.id, p.message, u.id AS user_id, u.name AS user_name FROM Posts p INNER JOIN Users u ON p.user = u.id ORDER BY u.name DESC LIMIT 10;
对应的GraphQL resolve逻辑(以Node.js + Sequelize ORM为例):
var RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { topPosts: { type: new GraphQLList(PostType), async resolve() { console.info("RootQuery topPosts resolve called."); // 用ORM关联查询并排序分页 return await Posts.findAll({ include: [{ model: Users }], order: [[Users, 'name', 'DESC']], limit: 10 }); } } } });
测试查询示例
定义好Schema后,用下面的GraphQL查询就能拿到结果:
query GetTopPosts { topPosts { id message user { id name } } }
小提示
- 排序时如果需要忽略大小写,可以把
name转成小写后比较:postB.user.name.toLowerCase().localeCompare(postA.user.name.toLowerCase()) - 如果需要支持动态排序(比如让客户端选择升序/降序),可以给
topPosts添加orderBy参数,在resolve里根据参数调整排序逻辑。
内容的提问来源于stack exchange,提问作者Pankaj Vishwani
相关产品推荐
相关产品推荐

