Bookshelf.js set attribute not in database

ⅰ亾dé卋堺 提交于 2019-12-07 04:51:38

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/29425746/bookshelf-js-set-attribute-not-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!