Bookshelf.js设置属性不在数据库中 [英] Bookshelf.js set attribute not in database
问题描述
我有一个Bookshelf.js模型。我希望能够为此模型设置和获取在数据库中不持久的属性。
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));
}
});
使用如下模式:
knex.schema.createTable('domains', function (table) {
table.increments().index();
table.text('name').index();
table.timestamps();
});
我希望能够保存名为url的属性,然后再将url解析为域之前它节省了。
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()
我收到错误消息:
"column \"url\" of relation \"domains\" does not exist"
我看了看。我找不到任何方法来将非持久性属性添加到bookshelf.js模型中。我也找不到任何关于将自定义getter和setter方法添加到bookshelf.js模型的内容。
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.
感谢任何帮助或见解!
推荐答案
在我的手机上,请原谅简短的回复,但你想要的是虚拟或复合字段。
On my phone, so forgive the short reply, but what you want is called 'virtual' or 'composite' fields.
https://github.com/tgriesser/bookshelf/ wiki /插件:-Virtuals
每个数据库映射器都有它们,但当你不知道它们被称为什么时,谷歌解决方案难以理解。
Every database mapper has them, but when you don't know what they're called it's understandably difficult to google a solution.
这篇关于Bookshelf.js设置属性不在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!