【发布时间】:2019-11-04 21:18:14
【问题描述】:
我正在创建现有 API 的 GraphQL 实现。我正在使用 Laravel 5.8 和 Lighthouse 3.7。
我想知道如何使用它来实现搜索功能 - 类似于...
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
}
用户搜索.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"
我知道出了什么问题 - resolve 函数中的 $users 返回一个可交互的对象 - 而不是一个模型 - 如 hasMany 或 belongsTo 返回。我想知道这样做的正确方法是什么。
【问题讨论】:
-
你可能需要一些
->join('cities')(左?)在解析器中 -
您尝试做的事情应该可以在不使用自定义解析器的情况下完成。只需在您的参数上使用
eq指令而不是lighthouse-php.com/3.7/api-reference/directives.html#eq
标签: php laravel graphql laravel-lighthouse