Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bookshelf.js orderby items randomly using rand()

I am using bookshelf.js to develop a project using mariaDB. I want to get my post items ordered randomly. I found this solution works for knex.js

knex('posts').select('id', 'text')
            .orderByRaw('RAND()')
            .limit(100)

But I want to do the same thing with Bookshelf.

like image 372
Salar Avatar asked Sep 13 '25 18:09

Salar


1 Answers

According to bookshelf.js documentation, model.query() returns the underlying knex query builder which you can apply your knex solutions to.

Post.query(function (qb) {
            qb.select('id',  'text');
            qb.orderByRaw('RAND()')
            qb.limit(2);
        }).fetchAll()
like image 141
Pouya Khalilzad Avatar answered Sep 16 '25 09:09

Pouya Khalilzad