我正在创建一个现有应用程序接口的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
}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;
}这是可行的--但只适用于查询返回的字段。
{
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那样返回的模型。我想知道怎样做才是正确的。
发布于 2019-06-26 05:27:56
您尝试做的事情不需要使用自定义的解析器也是可能的。
您应该能够使用如下所示的内容来完成此操作
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
}在这里,我们使用paginate method并使用一些constraints对其进行扩展。
发布于 2021-06-18 17:34:18
我在整个项目中尝试的最好方法是在User模型中添加一个公共静态scopeSearch函数并在那里执行搜索,然后轻松地使用以下代码进行搜索:
users(q: String @search): [User]
@paginate(model: "App\\Models\\User")@search将在您的模型中触发搜索功能。
https://stackoverflow.com/questions/56713311
复制相似问题