Reputation: 2096
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...
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
}
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.
Upvotes: 3
Views: 3448
Reputation: 519
The best way that I've tried throughout my project is to add a public static scopeSearch
function in the User
model and perform search there, and then easily use the code below to do the search:
users(q: String @search): [User]
@paginate(model: "App\\Models\\User")
The @search
will trigger the search function in your model.
Upvotes: 1
Reputation: 1866
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.
Upvotes: 2