Dan Pouliot
Dan Pouliot

Reputation: 415

bookshelfJS: idAttribute to specify alternate id name

I've added the idAttribute line to this code in hopes that it will allow me to specify an alternate name for my id field:

bookshelf.ApiUser = Bookshelf.Model.extend({
    tableName: 'users',
    idAttribute: 'userID'
});

but it breaks my node project. As long as my id field is named 'id', the project works; how can I name the id field userID and have bookshelfjs know what to do?

Upvotes: 1

Views: 2022

Answers (1)

vbranden
vbranden

Reputation: 5986

The value of idAttribute needs to be a column in the table. The purpose of it is to tell bookshelf which column it should use as the id field for thing like forge and relations. You cannot change the name of the field by specifying a different name there. The only way that I know how to change the field name in the model is to change the actual column name

----- UPDATE ----

Not that anyone cares, but you can work around this issue by using the virtual and hidden plugins to hide the actual id attribute and provide a virtual one with the different name.

first include the plugins

var bookshelf = require('bookshelf');
bookshelf.plugin('virtuals');
bookshelf.plugin('visibility');

then define your model with the id attribute as hidden and the virtual attribute to get/set the id attribute

bookshelf.ApiUser = Bookshelf.Model.extend({
    tableName: 'users',
    hidden: ['id'],
    virtuals: {
        userID: {
            get: function() {
                return this.get('id');
            },
            set: function(value) {
                return this.set('id', value);
            }
        }
    }
});

you will still need the id field named 'id' in the database. or you can just rename the primary key in the database to userID.

Upvotes: 2

Related Questions