Skip to content

Instantly share code, notes, and snippets.

@ricardograca
Last active January 15, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ricardograca/9343668dbb8444f7e297 to your computer and use it in GitHub Desktop.
Save ricardograca/9343668dbb8444f7e297 to your computer and use it in GitHub Desktop.
Bookshelf bug - belongsToMany and fetchAll
{
"name": "bookshelf-bug",
"version": "0.1.0",
"dependencies": {
"bookshelf": "*",
"bluebird": "*",
"knex": "*",
"sqlite3": "*"
}
}
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