folkloreinc / laravel-graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.
1.76k stars 233 forks source link

How to use GraphQL UnionType?? #387

Open caizhigang97 opened 6 years ago

caizhigang97 commented 6 years ago

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~

zettamax commented 6 years ago

Same problem, can anyone help with that?

mfn commented 5 years ago

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
    }
  }
}