如何使用Bookshelf获取行数?

时间:2017-06-02 15:53:15

标签: node.js knex.js bookshelf.js

如何获得行数(没有任何过滤器)?

我已经尝试了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);

1 个答案:

答案 0 :(得分:1)

试试这个:

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