2

I see 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();

Or like RAND() in MySQL:

SELECT col1, col2
FROM mytable
ORDER BY RAND();
Ryan
  • 22,332
  • 31
  • 176
  • 357

1 Answers1

2

Currently it is not possible out of the box with lighthouse since there is no RAND SortOrder Enum.

You could use a scope for that.

Suppose you want to grab randomly some users from your table. Create a scope in you user query in your schema.graphql

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

Create the scope in your 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();
 }

// ...

Utilize the scope in your query:

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

This is fine for small datasets but keep in mind that for larger datasets this could be a possible performance bottleneck.

miron
  • 1,361
  • 1
  • 11
  • 24
  • This worked! I really appreciate it. Now I just need to find a way to have my `gql` include its `orderBy` object variable (which has keys `field` and `order`) only when the `random` variable is false. – Ryan Jun 20 '20 at 20:16