GraphQL和石墨烯 [英] GraphQL and Graphene
问题描述
我有一个具有一对多关系的数据库架构.例如一个部门有很多客户.是否有可能创建一个客户和一个部门并将其关联的变异?还是正确的方法是先创建一个客户,然后再创建一个部门,然后彼此关联?
I have a database schema that has a one to many relationship. For e.g. one department has many customer. Is it possible to have a mutation that create a customer and a department and associate them? Or the correct way is to create a customer than a department and then associate each other?
在第二种方法中,我需要三趟而不是一趟.有人可以给我提供GraphQL来处理这种情况吗?
In the second approach I need to make three trips instead of one. Can someone provide me a GraphQL handling this situation?
推荐答案
您可以定义您的变异输入以支持嵌套类型.这样一来,您就可以在单个突变中同时发送部门
和 Customer
.
You can define your mutation input to support nested types. This will allow you to send both Department
and Customer
in a single mutation.
在返回有效载荷中,您可以在查询中指定返回新创建的部门
及其关联的 Customer
.
In the return payload, you can specify in your query to return the newly created Department
and it's associated Customer
.
class Customer(graphene.ObjectType):
customer_id = graphene.Int(required=True)
name = graphene.String(required=True)
class Department(graphene.ObjectType):
department_id = graphene.Int(required=True)
name = graphene.String(required=True)
customers = graphene.List(Customer)
class CustomerInput(graphene.InputObjectType):
name = graphene.String(required=True)
class DepartmentMutation(graphene.relay.ClientIDMutation):
class Input:
name = graphene.String(required=True)
customer = graphene.Field(CustomerInput)
department = graphene.Field(Department)
@classmethod
def mutate_and_get_payload(cls, input, context, info):
new_department_name = input.get('name')
new_customer = input.get('customer')
logger.debug(new_department_name)
logger.debug(new_customer)
# validate and persist...
# we return dummy objects for brevity
customer = Customer(
customer_id=1,
name=new_customer.get('name')
)
department = Department(
department_id=1,
name=new_department_name,
customers=[customer]
)
return cls(department=department)
您将允许您在一次旅行中进行变异和查询相关实体.
You will allow you to mutate and query for associated entities in one trip.
如果使用 Connections
定义关系,事情会变得有些复杂,但是基本原理是相同的.
Things get a bit complex if you're using Connections
to define the relationship, but the basic principle is the same.
这篇关于GraphQL和石墨烯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!