如何使用 Bookshelf 获取行数?

How do I get the count of rows using Bookshelf?

如何获取行数(不使用任何过滤器)?

我试过 User.fetch().count()User.count(),但我分别遇到了这些错误:

TypeError: User.fetch is not a function

AssertionError: expected { Object (_bitField, _fulfillmentHandler0, ...) } to equal 0

这是我的模型:

let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('User', User);

试试这个:

const knex = require("knex")(require("./knexfile").development);
const Bookshelf = require("bookshelf")(knex);

const User = Bookshelf.Model.extend({
  tableName: "user",
  idAttribute: "userid"
});

knex.migrate.latest().then(_ => {

  User.forge().count().then(ret => {
    console.log(ret);
    process.exit(0);
  });

});

输出应该是:

[sombriks@sephiroth sample-knex-bookshelf]$ node index.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs
.org/#Builder-insert).
3
[sombriks@sephiroth sample-knex-bookshelf]$

如果您需要更详细的信息,请查看 this repo