Lighthouseを使いMutaionで更新する際、
該当レコードを検索して
→該当なし=新規作成
→1件該当=更新
→複数件該当=該当レコードを削除して新規追加(該当を1レコードだけにする)
みたいな事を1リクエストで完結したかった。
処理内容
Versionを検索して
該当なしはレコード新規作成
1件該当があればレコード更新
それ以外は該当レコードを削除して新規作成
該当レコードのidを返却する
以下、ソース抜粋
schema.graphql
type mutation {
searchUpdateVersions(
ptype: String!
module: String!
performer: String!
version: String!
): VersionIdResponse
@field(resolver: "App\\GraphQL\\Mutations\\SearchUpdateVersion@handle")
}
type VersionIdResponse{
id: ID!
}
SearchUpdateVersion.php
<?php
namespace App\GraphQL\Mutations;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Version;
class SearchUpdateVersion
{
public function handle(
$rootValue,
array $args,
GraphQLContext $context = null,
ResolveInfo $resolveInfo
) {
$query = Version::query();
$query->where('ptype', $args['ptype']);
$query->where('module', $args['module']);
$query->where('performer', $args['performer']);
$versions = $query->get();
$version = new Version;
switch($versions->count()){
case 0:
break;
case 1:
$version = $versions[0];
if($version->version==$args['version']){
$id = $version->id;
return compact('id');
}
break;
default :
foreach($versions as $obj)
{
$obj->delete();
}
break;
}
$version->fill($args);
$version->save();
$id = $version->id;
return compact('id');
}
}