【问题标题】:How to shuffle results in Lighthouse GraphQL (order by random)?如何在 Lighthouse GraphQL 中打乱结果(随机排序)?
【发布时间】:2020-10-03 06:47:45
【问题描述】:

我看到了docs for @orderBy,但很好奇如何随机排序我的 Lighthouse GraphQL 结果,有点像Laravel 中的inRandomOrder

$randomUser = DB::table('users')
            ->inRandomOrder()
            ->first();

或者像 MySQL 中的 RAND()

SELECT col1, col2
FROM mytable
ORDER BY RAND();

【问题讨论】:

    标签: graphql laravel-lighthouse


    【解决方案1】:

    由于没有RANDSortOrder 枚举,目前不可能使用灯塔开箱即用。

    您可以为此使用范围。

    假设您想从表中随机抓取一些用户。在 schema.graphql 中的用户查询中创建范围

    type Query {
        posts(
            random: Boolean @scope(name: "random")
        ): [User!]!
    }
    

    在您的App\User.php 中创建范围:

    
    // ...
    
    /**
     * Shuffles the users randomly
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
     public function scopeRandom($query) {
        return $query->inRandomOrder();
     }
    
    // ...
    
    

    在查询中使用范围:

    {
      users(random: true) 
      {
        id,
        email,
        username
      }
    }
    

    这对于小型数据集很好,但请记住,对于较大的数据集,这可能是性能瓶颈。

    【讨论】:

    • 这成功了!对此,我真的非常感激。现在我只需要找到一种方法让我的gql 包含它的orderBy 对象变量(它有键fieldorder)只有当random 变量为假时。
    猜你喜欢
    • 2010-12-21
    • 2022-07-12
    • 2021-09-12
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多