Answer the question
In order to leave comments, you need to log in
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
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;
}
"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"]
}
mutation {
uoiModel(
input: {
id: 900003
status: 49
field: [
"id",
"status"
]
}
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question