E
E
ettychel2019-07-26 18:18:59
Laravel
ettychel, 2019-07-26 18:18:59

How to do insert ... on duplicate key update in Lighthouse-php on Laravel?

Good afternoon!
Recently I started to master lighthouse and GraphQL, and then the question immediately arose, how to make a mutation so that there is an insert or update query in the database? Laravel has a wonderful function Model::createOrUpdate($array), but I have no idea how to do it using lighthouse.
help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
ettychel, 2019-08-20
@ettychel

I solved my issue by creating a mutator class, all steps are described below
Add a package of custom data types
Create a mutator class
Along the path /yourPath/appName/app/GraphQL/Mutations the file ClassNameMutator.php will be created We
write our createOrUpdate method at the very end

use App\Models\ModelName;

...

public function createOrUpdate($rootValue, array $args, GraphQLContext $context)
{
    $model = ModelName::find($args['id']);
    if ($model == null) {$model = new ModelName();}
    $model->fill($args)->save();
    $model = ModelName::select($args['field'])->find($args['id']);

    return $model;
}

In the /yourPath/appName/graphql/schema.graphql file, write the following:
"A Json string with format normal Array"
scalar Mixed @scalar(class: "MLL\\GraphQLScalars\\Mixed")

 ...
    
type Mutation {
    uoiModel(input: uoi! @spread): Mixed @field(resolver: "[email protected]")
}
input uoi{
    id: ID!         //Поле таблицы в запрос
    otherField: ID  //Поле таблицы в запрос
    field: Mixed    //Поля, которые нужны в ответ, указываются в виде простого массива ["field1","field2","fieldn"]
}

Now we have a mutation that can be easily used, the query will be like this:
mutation {
    uoiModel(
        input: {
            id: 900003
            status: 49
            field: [
                "id",
                "status"
            ]
        }
    )
}

This solution is suitable for tables with both incremental id and without

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question