如何在 Lighthouse GraphQL 中打乱结果(随机排序)?

How to shuffle results in Lighthouse GraphQL (order by random)?

我明白了 docs for @orderBy but am curious how I could sort my Lighthouse GraphQL results randomly, kind of like inRandomOrder in Laravel:

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

或在MySQL中点赞RAND()

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

目前无法使用 lighthouse 开箱即用,因为没有 RAND SortOrder 枚举。

你可以为此使用范围。

假设您想从 table 中随机抓取一些用户。在 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
  }
}

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