Lighthouse GraphQL - how to self-reference User type for @belongsToMany?

576 Views Asked by At

I'm attempting to build a very simple Facebook clone to improve my knowledge of GraphQL. I'm using the nuwave/lighthouse package for my Laravel backend. Currently, when I run $user->friends()->get() in tinker, it correctly returns the results (so I know the model relationships are set up correctly at least).

Essentially, I have a User type that can have many Friends. I have a join table called friend_user that contains friend_id and user_id columns. When I try to run the query in GraphQL playground however, I receive the error "Class 'User' not found". How do I correctly self-reference a model/type?

User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class User extends Authenticatable
{
    // define relationships
    public function friends(): BelongsToMany
    {
        return $this->belongsToMany('User', 'friend_user', 'user_id', 'friend_id');
    }
}

user.graphql

extend type Query {
  friends: [User]! @field(resolver: "UserQuery@friends")
}

type User {
    id: ID!
    email: String!
    first_name: String
    last_name: String
    created_at: DateTime!
    updated_at: DateTime!

    friends: [User]! @belongsToMany(relation: "friends")
}

UserQuery.php

<?php

namespace App\GraphQL\Queries;

use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use GraphQL\Type\Definition\ResolveInfo;

class UserQuery
{
  /*
  * Return all of a user's friends
  */
  public function friends($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
  {
    $user = $context->user();

    if (!$user) {
      return [];
    }

    return $user->friends()->get();
  }
}
1

There are 1 best solutions below

0
On BEST ANSWER

Welp, 8 minutes after posting this, I figured it out (classic). I changed the belongsToMany definition up a bit to look like this:

public function friends(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
    }