GithubHelp home page GithubHelp logo

Comments (8)

chrissm79 avatar chrissm79 commented on July 29, 2024

In the resolve method of your query, wouldn't it just be:

public function resolve($root, $args, ResolveInfo $info)
{
    $fields = $info->getFieldSelection($depth = 3);

    $me = Auth::user(); // Or however you're handling finding "me"

    foreach ($fields as $field => $keys) {
        if ($field === 'friends') {
            $me->with('friends');
        }
    }

    return $me;
}

from laravel-graphql.

joshhornby avatar joshhornby commented on July 29, 2024

@chrissm79 How would I then call name on the friends?

from laravel-graphql.

chrissm79 avatar chrissm79 commented on July 29, 2024

You don't need to call "name" on friends, it just needs to be included in the array that is sent back from the resolve function (which you can do by eager loading the relationship).

If "friends" is a collection of the "User" model and it has a "name" attribute, it will automagically be sent back with the request. If "name" is actually the first_name and last_name attributes of the User model, then you could either use a mutator on the model or create a custom field.

If neither is the case I would need to see your Query and Type classes.

from laravel-graphql.

joshhornby avatar joshhornby commented on July 29, 2024

In this case in the me GraphQLType class how should I define friends in the fields() function?

from laravel-graphql.

chrissm79 avatar chrissm79 commented on July 29, 2024

You could do something like this (if it makes sense for your app):

MeType (which is the type your MeQuery would return)

namespace App\GraphQL\Types;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;

class MeType extends GraphQLType
{
    /**
     * Attributes of Type.
     *
     * @var array
     */
    protected $attributes = [
        'name' => 'Me',
        'description' => 'Authenticated user details.'
    ];

    /**
     * Available Field Types.
     *
     * @return array
     */
    public function fields()
    {
        return [
            'id' => [
                'type' => Type::id(),
                'description' => 'ID of user.'
            ],
            'name' => [
                'type' => Type::string(),
                'description' => 'Name of authenticated user.'
            ],
            'email' => [
                'type' => Type::string(),
                'description' => 'Email address of user.'
            ],
            'friends' => [
                // This is saying that friends is a "list" of the type "user"
                'type' => Type::listOf(GraphQL::type('user')),
                'description' => 'List of friends.'
            ]
        ];
    }
}

UserType

namespace App\Http\GraphQL\Types;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;

class UserType extends GraphQLType
{
    /**
     * Attributes of Type.
     *
     * @var array
     */
    protected $attributes = [
        'name' => 'User',
        'description' => 'User details.'
    ];

    /**
     * Available Field Types.
     *
     * @return array
     */
    public function fields()
    {
        return [
            'id' => [
                'type' => Type::id(),
                'description' => 'ID of user.'
            ],
            'name' => [
                'type' => Type::string(),
                'description' => 'Name of user.'
            ],
            'email' => [
                'type' => Type::string(),
                'description' => 'Email address of user.'
            ]
        ];
    }
}

In you graphql.php config file

'query' => [
    'me' => App\GraphQL\Queries\MeQuery::class,
    // ...
]
'types' => [
    'me' => App\GraphQL\Types\MeType::class,
    'user' => App\GraphQL\Types\UserType::class,
    // ...
]

from laravel-graphql.

joshhornby avatar joshhornby commented on July 29, 2024

@chrissm79 Thanks for the example. I seem to be getting a User Error: expected iterable, but did not find one. error. I will paste the code I have, my example is a user and a team:

The relationship is set in the User model:

public function team()
{
    return $this->belongsTo(Team::class);
}

UserType

class UserType extends GraphQLType
{
    protected $attributes = [
        'name' => 'User',
        'description' => 'User details.'
    ];

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::int()),
                'description' => 'The id of the user'
            ],
            'email' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The email of user'
            ],
            'team' => [
                'type' => Type::listOf(GraphQL::type('team')),
                'description' => 'Customer orders.',
            ]
        ];
    }
}

TeamType

class TeamType extends GraphQLType
{
    protected $attributes = [
        'name' => 'Team',
        'description' => 'Team the user belongs to.'
    ];

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::int()),
                'description' => 'The id of the team'
            ],
            'name' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The name of team'
            ]
        ];
    }
}

UsersQuery

class UsersQuery extends Query
{
    protected $attributes = [
        'name' => 'Users query'
    ];

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

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

    public function resolve($root, $args, ResolveInfo $info)
    {
        $fields = $info->getFieldSelection($depth = 5);

        $users = User::query();

        foreach ($fields as $field => $keys) {
            if ($field === 'team') {
                $users->with('team');
            }
        }

        if(isset($args['id']))
        {
            return User::where('id' , $args['id'])->get();
        }
        else if(isset($args['email']))
        {
            return \User::where('email', $args['email'])->get();
        }
        else
        {
            //return User::all();
        }
        // If I dd($users->get())); here I see the data loaded in the relationship
        return $users->get();
    }
}

This returns an error saying User Error: expected iterable, but did not find one.

from laravel-graphql.

joshhornby avatar joshhornby commented on July 29, 2024

I fixed this by looking at the code example by @chrissm79 in this issue #16.

My fields() now looks like:

'team' => [
    'type' => Type::listOf(GraphQL::type('team')),
    'description' => 'Customer orders.',
    'resolve' => function($data, $args) {
        return $data->team()->get();
     }
],

from laravel-graphql.

kendrawalker avatar kendrawalker commented on July 29, 2024

Hello @joshhornby I am new to graphql. I am currently working on a project with laravel and graphql as well. I am having issues querying a table based on a foreign key value. I see you had a similar problem.

I see in your project, you wrote this:

query FetchUser{
    user(id: 123456789) {
        id
        posts(id: 987654321) {
            id
        }
    }
}

In my project, I wrote a similar query:

plenty_systems{
    id,
    url,
    username,
    password,
    customer (id:${custID}) {
      id
    }
  }

However, my system is returning errors. Do you have any advice for me?

from laravel-graphql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.