folkloreinc / laravel-graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use GraphQL UnionType??

caizhigang97 opened this issue · comments

Hello everyone! Please look at the code:

<?php
namespace App\GraphQL\Query;

use Folklore\GraphQL\Support\Query;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use GraphQL;
class RecommandsQuery extends Query
{
    protected $attributes = [
        'name' => 'RecommandsQuery',
    ];
    public function type()
    { 
        return GraphQL::type('RecommandUnion');
    }
    public function args()
    { 
        return [
            'filter'                => [
                'name' => 'filter', 
                'type' => GraphQL::type('FollowFilter'),
            ],
        ]; 
    }
    public function resolve($root, $args, $context, ResolveInfo $info)
    {
        $qb = \App\Follow::orderBy('id', 'desc');

        $qb->when(isset($args['filter']), function ($q) use ($args) {
            switch ($args['filter']) {
                case 'CATEGORY':
                    return $q->where('followed_type', 'categories');
                case 'COLLECTION':
                    return $q->where('followed_type', 'collections');
                default:
                    break;
            }
        });
        return $qb->first()->followed;
    }
}
<?php

namespace App\GraphQL\Type;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\UnionType as BaseUnionType;

class RecommandUnionType extends BaseUnionType
{
    protected $attributes = [
        'name' => 'RecommandUnion',
        'description' => 'union'
    ];

    public function types()
    {
        return [
            GraphQL::type('Category'),
            GraphQL::type('Collection'),
        ];
    }

    public function resolveType($root)
    {
    	if($root->followed_type == 'categories'){
    		return GraphQL::type('Category');
    	}
       	return GraphQL::type('Collection');
    }
}

image

Can not run,How to define multi-type result?
Thanks~

Same problem, can anyone help with that?

You can use the fragment syntax to discriminate from which of the union types you want to query the fields, e.g. see https://facebook.github.io/graphql/June2018/#sec-Unions :

union SearchResult = Photo | Person

type Person {
  name: String
  age: Int
}

type Photo {
  height: Int
  width: Int
}

type SearchQuery {
  firstSearchResult: SearchResult
}

Query:

{
  firstSearchResult {
    ... on Person {
      name
    }
    ... on Photo {
      height
    }
  }
}