Laravel GraphQL之Mutation

2018年6月16日18:36:03 实习第七周 XXM

Begin

首先通过artisan命令快速创建一个Muatation

php artisan make:graphql:mutation UpdateUserMutation

返回类型

public function type()
{
    return GraphQL::Type('user');
}

UpdateUserMutation.php

<?php

namespace App\GraphQL\Mutation;

use Folklore\GraphQL\Support\Mutation;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use GraphQL;
use App\User;

class UpdateUserMutation extends Mutation
{
    protected $attributes = [
        'name' => 'UpdateUserMutation',
        'description' => 'A mutation'
    ];

    public function type()
    {
        return GraphQL::Type('user');
    }

    public function args()
    {
        return [
            'id'=>['name'=>'id','type'=>Type::nonNull(Type::int())],
            'userAccount'=>['name'=>'userAccount','type'=>Type::nonNull(Type::string())],
            'userPass'=>['name'=>'userPass','type'=>Type::nonNull(Type::string())],
            'email'=>['name'=>'email','type'=>Type::nonNull(Type::string())]
        ];
    }

    public function resolve($root, $args, $context, ResolveInfo $info)
    {
        $user=User::find($args['id']);

        if(!$user)
        {
            return null;
        }

        $user->userAccount=$args['userAccount'];

        $user->userPass=$args['userPass'];

        $user->email=$args['email'];

        $user->save();

        return $user;
    }
}

在配置文件 config/graphql.php 中新增变更配置:

'schemas' => [
        'default' => [
            'query' => [

            ],
            'mutation' => [
                'updateUser'=>'\App\GraphQL\Mutation\UpdateUserMutation',
            ]
        ]
    ],

然后通过GraphiQL进行测试

20180612113053379.png

End

日记本

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

赞赏支持
被以下专题收入,发现更多相似内容