通过一次请求,在Lighthouse中搜索并更新Mutation

在使用 Lighthouse 进行 Mutaion 更新时,
首先要搜索相应的记录,
→ 没有找到符合条件的记录=创建新记录
→ 找到一条符合条件的记录=更新
→ 找到多条符合条件的记录=删除这些记录并新增一条新记录(只保留一条符合条件的记录)
我希望在一个请求中完成以上操作。

处理内容

搜索版本
如果没有找到任何相关记录,创建新记录
如果有一条相关记录,更新记录
否则,删除相关记录并创建新记录
返回相关记录的id

以下为源代码摘录。



type mutation {
    searchUpdateVersions(
        ptype: String!
        module: String!
        performer: String!
        version: String!
    ): VersionIdResponse
        @field(resolver: "App\\GraphQL\\Mutations\\SearchUpdateVersion@handle")
}

type VersionIdResponse{
    id: ID!
}
<?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');
    }
}

我在中國內地常見的出色文章受益匪淺。

我尝试充分利用Laravel来使用GraphQL。

bannerAds