简体   繁体   English

Bookshelf.js设置属性不在数据库中

[英]Bookshelf.js set attribute not in database

I have a Bookshelf.js model. 我有一个Bookshelf.js模型。 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. 我希望能够保存名为url的属性,然后在保存之前将url解析为域。

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. 我找不到任何方法来将非持久性属性添加到bookshelf.js模型中。 I also couldn't find anything about adding custom getter and setter methods to a bookshelf.js model. 我也找不到任何关于向bookshelf.js模型添加自定义getter和setter方法的信息。

Any help or insight is appreciated! 任何帮助或见解表示赞赏!

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 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. 每个数据库映射器都有它们,但是当你不知道它们被称为什么时,谷歌解决方案很难理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM