Bookshelf.js orderby items randomly using rand()

Viewed 2519

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.

2 Answers

Maybe this answer will be helpful to someone :

//with where 
    let val = await Question.where({'test_id': id}).query(function (qb) {
                qb.limit(1);//with limit
                qb.orderByRaw('RAND()')//with rand
            }).fetchAll({
                withRelated: ['answers', 'comments'], require: true
            });
Related