- 
      
- 
        Save qawemlilo/429eabfed98ba1fcd17e to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | var Promise = require('bluebird'), | |
| User = require('./user'), | |
| knex, query; | |
| knex = User.prototype._builder(User.prototype.tableName); | |
| query = function (q) { | |
| q.distinct() | |
| .innerJoin('orders', function () { | |
| this.on('users.id', '=', 'orders.user_id') | |
| .andOn('orders.amount', '>', 100); | |
| }) | |
| .innerJoin('addresses', function () { | |
| this.on('users.id', '=', 'addresses.user_id') | |
| .andOn('addresses.state', '=', 'New York'); | |
| }); | |
| return q; | |
| }; | |
| Promise.all([ | |
| query(knex.count()).first().then(function (row) { | |
| return +row.count; | |
| }), | |
| User.query(query).fetchAll({ withRelated: ['orders', 'addresses'] }) | |
| ]).spread(function (count, users) { | |
| // success | |
| }); | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | var Promise = require('bluebird'); | |
| Model.countAndFetch = function (query, options) { | |
| return Promise.all([ | |
| query(knex.count()).first().then(function (row) { | |
| return +row.count; | |
| }), | |
| this.query(query).fetchAll(options) | |
| ]); | |
| }; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | User.query(function (q) { | |
| q.distinct() | |
| .innerJoin('orders', function () { | |
| this.on('users.id', '=', 'orders.user_id') | |
| .andOn('orders.amount', '>', 100); | |
| }) | |
| .innerJoin('addresses', function () { | |
| this.on('users.id', '=', 'addresses.user_id') | |
| .andOn('addresses.state', '=', 'New York'); | |
| }); | |
| }) | |
| .fetchAll({ withRelated: ['orders', 'addresses'] }) | |
| .then(function (users) { | |
| var user = users.at(0), | |
| orders = user.related('orders'), | |
| addresses = user.related('addresses'); | |
| // do stuff with the user, their orders, and their addresses | |
| }); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment