bookshelf.js count method

后端 未结 6 914
星月不相逢
星月不相逢 2021-02-14 01:20

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

6条回答
  •  天命终不由人
    2021-02-14 02:03

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

提交回复
热议问题