Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bookshelf.js count method

I was searching high and low to find how to do basic counting (like SELECT COUNT(something) FROM table) with Bookshelf.js, but to no avail. Is there anything I'm missing? Or is it just used with a manual select query?

Thanks!

like image 503
zbrox Avatar asked Jan 28 '14 12:01

zbrox


Video Answer


2 Answers

Since version 0.8.2 you can just use the Collection#count() method:

User.collection().count().then(function(count) {
  // count === 15
})

This can be used on any collection, like a model's relation:

User.forge({id: 1}).related('comments').count().then(function(count) {
  // count === 16
})

It can also be used on Model classes as a static method:

User.count().then(function(count) {
  // count === 15
})

It also accepts a column name to filter the results of the count by excluding rows whose value is NULL and will take into consideration any other defined query constraints:

User.count('is_active').then(function(count) {
  // count === 8
})

User.where('status', 'single').count().then(function(count) {
  // count === 4
})
like image 196
devius Avatar answered Sep 19 '22 21:09

devius


//user.js
var db = require('./db');
var User = db.Model.extend({  
  tableName: 'users',
  hasTimestamps: true,
});
module.exports = User; 

//main.js
var User = require('./user');
User.where('pet', 'dog').count('*').then(function(count) {
  console.log("Total Count : " , count);
});

In the above code snippet User is a model having the attributes like pet and name.

The generated query will be as follows: select count(*) from user where pet='dog';

like image 31
Reyansh Avatar answered Sep 17 '22 21:09

Reyansh