如何减少草莓GraphQl和FastApi中一对一关联的数据库查询数量?
我正在使用FastAPI和Strawberry开发Python GraphQl API服务器,并且正在实现此功能: 我有两个实体,即用户和订单,它们具有一对多关联(用户可以有很多订单,订单只能有一个用户),我想获取一个用户列表,每个订单列表。
如果我要用简单的休息端点来实现此功能,我可以进行第一个查询以获取用户,然后在Python代码中进行第二个查询,以获取订单,并根据每个订单属于的用户基于外国订单属于钥匙值。
不过,使用草莓GraphQl,看来我无法避免为每个用户进行查询,鉴于,即使使用数据加载器模式,我仍然需要事先知道订单ID,这使响应时间较慢。
有解决这个问题的解决方案吗?我的方法完全错了吗?
I'm developing a python GraphQL API server using FastAPI and Strawberry, and I'm implementing this feature:
I have two entities, User and Order, which have a one to many association (a User can have many Orders, an Order can only have one User), and I want to get a list of users, each with the list of their orders.
If I were to implement this with a simple REST endpoint, I could make a first query to get the users and then a second query to fetch the orders, sorting out, in the python code, which user each order belongs to based on the foreign key value.
Using Strawberry GraphQL though, it seems I cannot avoid making a query for each user, given that, even using the data loader pattern I would still need to know the order ids beforehand, and this is making the response time much slower.
Is there a solution to this problem? Is my approach completely wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数据加载器功能本身可以进行分组。
该想法上的变体:
The data loader function itself can do the grouping.
Variants on that idea: