Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const _ = require('lodash');
- const Util = require('util');
- const Knex = require( 'knex' )( require('./config').database );
- const Bookshelf = require('bookshelf')( Knex );
- var Server = Bookshelf.Model.extend({
- tableName: 'servers',
- hasTimestamps: true,
- operating_system: function() {
- return this.belongsTo( OS );
- },
- application: function(){
- return this.belongsToMany( Application );
- }
- });
- var OS = Bookshelf.Model.extend({
- tableName: 'operating_systems',
- hasTimestamps: true,
- server: function() {
- return this.hasMany( Server );
- }
- });
- var Application = Bookshelf.Model.extend({
- tableName: 'applications',
- hasTimestamps: true,
- appServer: function() {
- return this.belongsToMany( Server );
- }
- });
- function termKnex(){
- return Promise( ( res, req ) => {
- Knex.destroy( () => {
- console.log( 'Terminated Connection pool' );
- res();
- } );
- });
- }
- function selectAllAndUpdate() {
- new Server()
- .fetchAll( {
- withRelated: [ 'operating_system', 'application' ]
- } )
- .then( result => {
- console.log(result.toJSON());
- } )
- .catch( err => {
- console.log( 'Query Error:', err );
- Knex.destroy( () => {
- console.log( 'Terminated Connection pool' );
- } );
- } );
- }
- selectAllAndUpdate();
- /**
- * The above results in the following queries:
- * 3 Query select `servers`.* from `servers`
- * 3 Query select `operating_systems`.* from `operating_systems` where `operating_systems`.`id` in (1, 2, 3, 4)
- * 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)
- */
Advertisement
Add Comment
Please, Sign In to add comment