问题
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?
In the second approach I need to make three trips instead of one. Can someone provide me a GraphQL handling this situation?
回答1:
You can define your mutation input to support nested types. This will allow you to send both Department
and Customer
in a single mutation.
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.
Things get a bit complex if you're using Connections
to define the relationship, but the basic principle is the same.
来源:https://stackoverflow.com/questions/41345377/graphql-and-graphene