bookshelf.js检索模型名称&通过virtuals-plugin将其分配给实例#beginner。

问题描述 投票:0回答:1

我觉得这是个非常愚蠢的问题,但尽管我很努力,但我自己也没有接近解决这个问题。

所以,我们开始吧。

我安装& 设置虚拟插件。

bookshelf.plugin('bookshelf-virtuals-plugin');

然后是定义getter。

...bookshelf.model(
  'MasterModel',
  {
    virtuals: {
      type() { return this.constructor.name; }
    }
  ...
  });
...

之后,我扩展这个主模型,并定义其他模型。希望能够通过类似这样的方式来检索当前变量是链中最后一个模型的实例的名称。instance.get('type').

我推测在bookshelf的身上肯定有一个属性方法 Model 对象的访问,但在api文档中没有找到。

PS. 我之所以使用虚拟的,是因为我希望跳过管理序列化机制的 toJSON().

bookshelf.js
1个回答
0
投票

如果你只想确定一个模型是否属于某种类型,你只需要这个。

const MyModel = bookshelf.model('MyModel')

// next some place where you need to check the model type
if (anotherModel instanceof MyModel) {
  // do stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.