簡體   English   中英

在 Laravel/Lighthouse GraphQL API 中實現搜索功能

[英]Implementing Search funtionality in Laravel/Lighthouse GraphQL API

我正在創建現有 API 的 GraphQL 實現。 我在 Lighthouse 3.7 中使用 Laravel 5.8。

我想知道如何使用它來實現搜索功能 - 類似於......

方案.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"

我知道了什么錯誤-在$usersresolve函數返回一個interatable對象-而不是一個模型-樣hasManybelongsTo的回報。 我想知道這樣做的正確方法是什么。

在不使用自定義解析器的情況下,您嘗試執行的操作應該是可能的。

您應該能夠使用以下類似的東西來做到這一點

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 方法並使用一些約束對其進行擴展。

我在整個項目中嘗試過的最好方法是在User模型中添加一個公共靜態scopeSearch函數並在那里執行搜索,然后輕松使用下面的代碼進行搜索:

users(q: String @search): [User]
@paginate(model: "App\\Models\\User")

@search將觸發模型中的搜索功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM