在Laravel / Lighthouse GraphQL API中实现搜索功能

I'm creating a GraphQL implementation of an existing API. I'm using Laravel 5.8 with Lighthouse 3.7.

I'm wondering how to implement a search functionality using this - something along the lines of...

scheme.graphql

type Query {
    userSearch(name: String, email: String, phone: String, city_id: Int): [User] #Custom Resolver - app/GraphQL/Queries/UserSearch.php
}
type User {
    id: ID!
    name: String!
    email: String
    phone: String
    credit: Int
    city_id: Int
    city: City @belongsTo
}

UserSearch.php

public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
{
    $q = app('db')->table('users');
    foreach($args as $key => $value) {
        $q->where($key, $value);
    }
    $users = $q->get();

    return $users;
}

This would work - but only for the fields that are returned by the query.

{
    userSearch(name:"Picard") {
        id          # This will work
        name        # This will work
        city {      # These wont.
            id      # These won't work
            name    # These won't work
        }
    }
}

I'll get this error when I try it...

"debugMessage": "Argument 1 passed to Nuwave\\Lighthouse\\Schema\\Directives\\RelationDirective::Nuwave\\Lighthouse\\Schema\\Directives\\{closure}() must be an instance of Illuminate\\Database\\Eloquent\\Model, instance of stdClass given, called in /mnt/x/Data/www/Projects/Phoenix/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php on line 221"

I know what is going wrong - the $users in the resolve function is returning a interatable object - and not a model - like hasMany or belongsTo returns. I'm wondering what is the right way to do this.

What you are trying to do should be possible without using a custom resolver.

You should be able to do it with something in the likes of the following

type Query {
    userSearch(name: String @eq, email: String @eq, phone: String @eq, city_id: Int @eq): [User] @paginate
}
type User {
    id: ID!
    name: String!
    email: String
    phone: String
    credit: Int
    city_id: Int
    city: City @belongsTo
}

Here we utilize the paginate method and extending it with some constraints.