【问题标题】:Bookshelf.js orderby items randomly using rand()Bookshelf.js 使用 rand() 随机排序项目
【发布时间】:2017-07-17 20:37:33
【问题描述】:

我正在使用 bookshelf.js 开发一个使用 mariaDB 的项目。我想随机订购我的帖子。我发现这个解决方案适用于 knex.js

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

但我想对 Bookshelf 做同样的事情。

【问题讨论】:

  • 其实它的random()不是rand(),只是想说

标签: mysql knex.js bookshelf.js


【解决方案1】:

根据 bookshelf.js 文档,model.query() 返回底层 knex 查询构建器,您可以将 knex 解决方案应用到该构建器。

Post.query(function (qb) {
            qb.select('id',  'text');
            qb.orderByRaw('RAND()')
            qb.limit(2);
        }).fetchAll()

【讨论】:

    【解决方案2】:

    也许这个答案会对某人有所帮助:

    //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
                });
    

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多