JSON API 嵌套资源相对于父级的标识符

JSON API identifiers for nested resources relative to parent

当一个人对资源关系进行建模时,给出的经典示例是 articlescomments。这变得易于建模,因为:

但是如何处理相关资源仅存在于父上下文中的情况?

例如,orderitems

在JSON-API中,关系对象需要"type"和"id"来指定链接:

"relationships": {
    "links": {
        "self": "http://example.com/orders/123/relationships/items",
        "related": "http://example.com/orders/123/items"
    },
    "data": {
        "type": <what goes here>,
        "id": <what goes here>
    }
}

数据的类型和 ID 需要与订单号 123 相关。当然,假设它们没有从数据库中分配 UUID 或类似的,因为它们实际上是一个组合键.它们主要作为外键组合存在。

如何处理?

关系的一个选项是使用 type 作为 order_item 和 id 作为散列或某种定界字符串连接的订单 ID 和项目 ID。 (例如 123_abc)。 123我从订单中得到,abc我从订单中的商品中得到。

除了完全避免提供资源链接之外,还有其他方法吗?

根据 JSON API 规范,每个资源必须由 typeid 的组合唯一标识:

Identification

Every resource object MUST contain an id member and a type member. The values of the id and type members MUST be strings.

Within a given API, each resource object’s type and id pair MUST identify a single, unique resource. (The set of URIs controlled by a server, or multiple servers acting as one, constitute an API.)

https://jsonapi.org/format/#document-resource-object-identification

因此,您不仅需要 resource linkage 的 ID,还需要构建任何有效的响应,包括此类资源。

但是没有关于如何为每种类型生成唯一 ID 的规则。如果您的数据模型不包含 ID,则将唯一订单 ID 与唯一商品 ID 组合以获得订单中每个商品的唯一 ID 似乎是一种很好的方法。