我正在创建现有 API 的 GraphQL 实现。我正在使用 Laravel 5.8 和 Lighthouse 3.7。
我想知道如何使用它来实现搜索功能 - 类似于......
方案.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
}
用户搜索.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;
}
这将起作用 - 但仅适用于查询返回的字段。
{
userSearch(name:"Picard") {
id # This will work
name # This will work
city { # These wont.
id # These won't work
name # These won't work
}
}
}
我尝试时会收到此错误...
"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"
我知道出了什么问题——函数$users
中resolve
的返回的是一个可交互的对象——而不是一个模型——比如hasMany
或belongsTo
返回。我想知道这样做的正确方法是什么。