GraphQL and Graphene

别说谁变了你拦得住时间么 提交于 2021-01-29 03:34:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!