Created
September 1, 2015 07:07
-
-
Save LordSputnik/2ce27c6f260685b74eef to your computer and use it in GitHub Desktop.
Minimal code demonstrating issue with idAttribute and relations in bookshelf.js
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 knex = require('knex')({ | |
client: 'postgresql', | |
connection: { | |
host : '127.0.0.1', | |
user : 'username', | |
password : 'password', | |
database : 'database' | |
} | |
}); | |
var Bookshelf = require('bookshelf')(knex); | |
var _ = require('underscore'); | |
_.str = require('underscore.string'); | |
function snakeToCamel(attrs) { | |
return _.reduce(attrs, function(result, val, key) { | |
result[_.str.camelize(key)] = val; | |
return result; | |
}, {}); | |
} | |
function camelToSnake(attrs) { | |
return _.reduce(attrs, function(result, val, key) { | |
result[_.str.underscored(key)] = val; | |
return result; | |
}, {}); | |
} | |
var UserType = Bookshelf.Model.extend({ | |
tableName: 'bookbrainz.user_type', | |
idAttribute: 'userTypeId', | |
parse: snakeToCamel, | |
format: camelToSnake | |
}); | |
var User = Bookshelf.Model.extend({ | |
tableName: 'bookbrainz.user', | |
idAttribute: 'userId', | |
parse: snakeToCamel, | |
format: camelToSnake, | |
hidden: ['password'], | |
userType: function() { | |
return this.belongsTo(UserType, 'user_type_id'); | |
} | |
}); | |
new User({userId: 4}).fetch({withRelated: ['userType']}).then(function() { | |
process.exit(); | |
}); | |
// Unhandled rejection error: | |
// select "bookbrainz"."user_type".* from "bookbrainz"."user_type" | |
// where "bookbrainz"."user_type"."userTypeId" in ($1) | |
// - column user_type.userTypeId does not exist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment