Skip to content

Support for OrderBy RANDOM() / r.sample() #43

@SlyDave

Description

@SlyDave

RethinkDb has sample() that allows returning x number of rows in a shuffled order.
(note: there is also random() but that is for maths operations)

e.g.:

r.db('database').table('table').sample(1);

This is equivalent to SELECT * FROM <table> ORDER BY RANDOM() LIMIT 1

Which is in turn equivalent to the eloquent:

$randomRow = DB::table('table')
                ->inRandomOrder()
                ->limit(1)
                ->first();

If you attempt to use inRandomOrder() with duxet/laravel-rethinkdb you get the following error:

at HandleExceptions->handleError(8, 'Undefined index: column', '/www/vendor/duxet/laravel-rethinkdb/src/Query/Builder.php', 130, array('order' => array('type' => 'Raw', 'sql' => 'RANDOM()'))) in Builder.php line 130
at Builder->compileOrders() in Builder.php line 80
at Builder->getFresh() in Builder.php line 117
at Builder->runSelect() in Builder.php line 1703
at Builder->get(array('*')) in Builder.php line 493
at Builder->getModels(array('*')) in Builder.php line 477
at Builder->get(array('*')) in Builder.php line 409

Because there is no handler for RANDOM() only ASC and DESC

            $compiled = strtolower($direction) == 'asc'
                ? r\asc($column) : r\desc($column);

If the statement being built has inRandomOrder() but no limit(), this is equivalent to:

r.db('database').table('table').sample(r.db('database').table('table').count());
and

$randomCollection = DB::table('table')
                ->inRandomOrder()
                ->all();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions