实现环回类表继承

Implementing Class Table Inheritance in Loopback

本文关键字:继承 实现      更新时间:2023-09-26

我正在尝试在环回模型中实现子类化,其中我有一个具有公共字段的父表和具有特定字段的父表的子表。

一个实际的例子:

Customer

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

  • internal_id
  • created

Person

仅包含个人特定字段的模型

  • first_name
  • last_name

Organisation

只有组织特定字段的模型

  • registration_number
  • trade_name

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

我遵循这个扩展模型的指南,在Customer模型的基础上创建PersonOrganisation模型

然而,当我创建一个Person,即通过POSThttp://0.0.0:3000/persons,他被创建在Person表,而不是在Customer表。

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

情况似乎并非如此。我如何在环回中实现这一点?


如果需要,这里是模型的json:

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不提供这种类型的继承。模型仅仅是模板,扩展模型只是创建一个新的模板,其中包含从继承模型中获得的属性/方法。

我明白你想抽象客户是个人还是组织。这看起来像是多态关系的典型用例。多态关系允许您将一个模型关联到其他几个模型。

下面是我将如何构建应用程序:

In customer.js

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

In person.js

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

In organization.js

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

我使用这个例子是因为环回文档不是很清楚