我有一个具有一对多关系的数据库模式。对于例如一个部门有很多客户。是否有可能创建客户和部门并将其关联起来?或者正确的方法是创建客户而不是部门,然后相互关联?
在第二种方法中,我需要进行三次而不是一次。 有人能为我提供处理这种情况的GraphQL吗?
答案 0 :(得分:1)
您可以定义突变输入以支持嵌套类型。这样您就可以在单个变异中发送Department
和Customer
。
在返回有效内容中,您可以在查询中指定返回新创建的Department
及其关联的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)
您将允许您在一次旅行中变异和查询关联实体。
如果您使用Connections
来定义关系,事情会变得有点复杂,但基本原则是相同的。