在 Loopback 中实现 Class Table 继承

Implementing Class Table Inheritance in Loopback

我正在尝试在 Loopback 模型中实现子类化,其中我的父 table 具有公共字段,table 是父 table 的子级特定领域。

实际例子:

Customer

具有适用于个人和组织的字段的模型

Person

只有个人特定字段的模型

Organisation

仅包含组织特定字段的模型


所以基本上 Person 继承自 CustomerOrganisation 也继承自 Customer

我已按照 Extending Models 的指南在 Customer 模型上创建 PersonOrganisation 模型 based

然而,当我创建一个 Person,即通过 POSThttp://0.0.0:3000/persons,他是在 Person table 而不是在 [=15] =] table.

我假设当我基于另一个模型扩展模型时,在保存扩展模型时它也会将公共字段保存到父模型中。

好像不是这样的。如何在 Loopback 中实现此目的?


如果需要,这里是模型 jsons:

customer.json

{
  "name": "Organisation",
  "plural": "Organisations",
  "base": "Customer",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "registration_number": {
      "type": "string",
      "required": true
    },
    "trade_name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

person.json

{
  "name": "Person",
  "plural": "Persons",
  "base": "Customer",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "first_name": {
      "type": "string",
      "required": true
    },
    "last_name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

organisation.json

{
  "name": "Organisation",
  "plural": "Organisations",
  "base": "Customer",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "registration_number": {
      "type": "string",
      "required": true
    },
    "trade_name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

Loopback 不提供这种类型的继承。模型只是模板,扩展模型只是创建一个新模板,其中 properties/methods 从继承的模型中获得。

我知道您想抽象客户是人还是 organization.This 看起来像 polymorphic relations 的典型用例。多态关系使您可以将一个模型与其他几个模型相关联。

以下是我构建应用程序的方式:

customer.js

{
  "name": "Customer",
  // ...
  "relations": {
    "customerable": {
      "type": "belongsTo",
      "polymorphic": true
    }
  }, // ...
}

person.js

{
  "name": "Person",
  // ...
  "relations": {
    "customer": {
      "type": "hasOne",
      "model": "Customer",
      "polymorphic": {"as": "customerable", "discriminator": "person"}
    }
  }, // ...
}

organization.js

{
  "name": "Organization",
  // ...
  "relations": {
    "orders": {
      "type": "hasOne",
      "model": "Customer",
      "polymorphic": {"as": "customerable", "discriminator": "organization"} 
    }
  }, // ...
}

我用了this example因为loopback doc不是很清楚