Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bookshelf.js set attribute not in database

I have a Bookshelf.js model. I want to be able to set and get attributes for this model that are not persistent in the database.

For instance lets say I have a model that looks like this:

var Domain = bookshelf.Model.extend({
      tableName: 'domains',
      initialize: function() {
        this.on('creating', this.setDomainName);
      },
      setDomainName: function() {
        this.set('name', getDomainFromUrl(this.url));
      }
    });

With a schema that looks like this:

knex.schema.createTable('domains', function (table) {
    table.increments().index();
    table.text('name').index();
    table.timestamps();
  });

I want to be able to save an attribute called url, then later parse the url into a domain before it saves.

When I try something like this:

new Domain({url: 'http://someurl.com/foo/bar'}).save()

I get the error message:

"column \"url\" of relation \"domains\" does not exist"

I've looked and looked. I cant find any way to add non-persistent attributes to a bookshelf.js model. I also couldn't find anything about adding custom getter and setter methods to a bookshelf.js model.

Any help or insight is appreciated!

like image 254
nmajor Avatar asked Apr 03 '15 03:04

nmajor


1 Answers

On my phone, so forgive the short reply, but what you want is called 'virtual' or 'composite' fields.

https://github.com/tgriesser/bookshelf/wiki/Plugin:-Virtuals

Every database mapper has them, but when you don't know what they're called it's understandably difficult to google a solution.

like image 117
coolaj86 Avatar answered Oct 31 '22 19:10

coolaj86