jLinux

Untitled

Dec 24th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const _         = require('lodash');
  4. const Util      = require('util');
  5. const Knex      = require( 'knex' )( require('./config').database );
  6. const Bookshelf = require('bookshelf')( Knex );
  7.  
  8.  
  9. var Server = Bookshelf.Model.extend({
  10.     tableName: 'servers',
  11.     hasTimestamps: true,
  12.     operating_system: function() {
  13.         return this.belongsTo( OS );
  14.     },
  15.     application: function(){
  16.         return this.belongsToMany( Application );
  17.     }
  18. });
  19.  
  20. var OS = Bookshelf.Model.extend({
  21.     tableName: 'operating_systems',
  22.     hasTimestamps: true,
  23.     server: function() {
  24.         return this.hasMany( Server );
  25.     }
  26. });
  27.  
  28. var Application = Bookshelf.Model.extend({
  29.     tableName: 'applications',
  30.     hasTimestamps: true,
  31.     appServer: function() {
  32.         return this.belongsToMany( Server );
  33.     }
  34. });
  35.  
  36. function termKnex(){
  37.     return Promise( ( res, req ) => {
  38.         Knex.destroy( () => {
  39.             console.log( 'Terminated Connection pool' );
  40.             res();
  41.         } );
  42.     });
  43. }
  44.  
  45. function selectAllAndUpdate() {
  46.     new Server()
  47.         .fetchAll( {
  48.             withRelated: [ 'operating_system', 'application' ]
  49.         } )
  50.         .then( result => {
  51.             console.log(result.toJSON());
  52.         } )
  53.         .catch( err => {
  54.             console.log( 'Query Error:', err );
  55.  
  56.             Knex.destroy( () => {
  57.                 console.log( 'Terminated Connection pool' );
  58.             } );
  59.         } );
  60. }
  61.  
  62. selectAllAndUpdate();
  63.  
  64.  
  65. /**
  66.  * The above results in the following queries:
  67.  *  3  Query    select `servers`.* from `servers`
  68.  *  3  Query    select `operating_systems`.* from `operating_systems` where `operating_systems`.`id` in (1, 2, 3, 4)
  69.  *  4  Query    select `applications`.*, `applications_servers`.`server_id` as `_pivot_server_id`, `applications_servers`.`application_id` as `_pivot_application_id` from `applications` inner join `applications_servers` on `applications_servers`.`application_id` = `applications`.`id` where `applications_servers`.`server_id` in (1, 2, 3, 4, 5, 6, 7, 8, 9)
  70.  */
Advertisement
Add Comment
Please, Sign In to add comment