问题
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