Last active
January 15, 2018 15:00
-
-
Save ricardograca/9343668dbb8444f7e297 to your computer and use it in GitHub Desktop.
Bookshelf bug - belongsToMany and fetchAll
This file contains 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
{ | |
"name": "bookshelf-bug", | |
"version": "0.1.0", | |
"dependencies": { | |
"bookshelf": "*", | |
"bluebird": "*", | |
"knex": "*", | |
"sqlite3": "*" | |
} | |
} |
This file contains 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') | |
var knex = require('knex')({ | |
client: 'sqlite3', | |
connection: {filename: ':memory:'}, | |
debug: true | |
}) | |
var bookshelf = require('bookshelf')(knex) | |
var Color = bookshelf.Model.extend({tableName: 'colors'}) | |
var Thing = bookshelf.Model.extend({ | |
tableName: 'things', | |
colors: function() { | |
return this.belongsToMany(Color, 'thing_colors') | |
} | |
}) | |
Promise.all([ | |
knex.schema.createTable('colors', function(table) { | |
table.increments() | |
table.text('name').notNullable() | |
}), | |
knex.schema.createTable('things', function(table) { | |
table.increments() | |
table.text('name').notNullable() | |
}), | |
knex.schema.createTable('thing_colors', function(table) { | |
table.increments() | |
table.integer('thing_id').notNullable().references('things.id') | |
table.integer('color_id').notNullable().references('colors.id') | |
}) | |
]).then(function() { | |
return [ | |
knex('things').insert({name: 'Noemie'}), | |
knex('colors').insert({name: '02 Blanc'}), | |
knex('colors').insert({name: '03 Rose'}), | |
knex('colors').insert({name: '01 Noir'}) | |
] | |
}).spread(function () { | |
// Bad path | |
return Promise.all([ | |
Thing.fetchAll({withRelated: ['colors']}), | |
Color.forge({id: 1}).fetch() | |
]) | |
// Good path | |
/* | |
return Promise.all([ | |
Thing.forge({id: 1}).fetch(), | |
Color.fetchAll() | |
]) | |
*/ | |
}).then(function(models) { | |
// Bad path | |
return models[0].at(0).related('colors').attach(models[1]) | |
// Good path | |
//return models[0].related('colors').attach(models[1].at(0)) | |
}).then(function() { | |
console.log('all done') | |
}).catch(function (err) { | |
console.log(err) | |
console.log(err.stack) | |
}).finally(function() { | |
process.exit() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment