JSON:API中lid字段使用场景的技术问询
关于JSON:API v1.1中
lid字段的非自关联使用场景 lid(本地ID)的实用场景不止创建带自关联的资源,它核心是解决客户端在批量创建关联资源时,能在请求内部临时关联尚未被服务器分配正式ID的新资源。下面是几个典型的非自关联示例:
1. 批量创建跨类型关联资源(一次请求创建多类型新资源并绑定关系)
比如同时创建一篇新文章和一个新作者,并直接将文章关联到该作者。由于两个资源都是新建状态,服务器还未分配正式ID,此时lid可用于在请求内部建立关联:
{ "data": { "type": "articles", "lid": "temp-article-001", "attributes": { "title": "JSON:API Lid 实战示例" }, "relationships": { "author": { "data": { "type": "authors", "lid": "temp-author-001" } } } }, "included": [ { "type": "authors", "lid": "temp-author-001", "attributes": { "name": "示例创作者" } } ] }
服务器处理时会先创建作者资源,再创建文章并绑定到该作者,最终返回带正式ID的资源,客户端可通过lid映射本地临时标识。
2. 创建带多对多关联的新资源
比如创建一门新课程,同时创建多个新学生,并将这些学生直接加入课程的学员列表:
{ "data": { "type": "courses", "lid": "temp-course-001", "attributes": { "name": "JSON:API 进阶实战" }, "relationships": { "students": { "data": [ { "type": "students", "lid": "temp-student-001" }, { "type": "students", "lid": "temp-student-002" } ] } } }, "included": [ { "type": "students", "lid": "temp-student-001", "attributes": { "name": "张三" } }, { "type": "students", "lid": "temp-student-002", "attributes": { "name": "李四" } } ] }
这里lid让客户端无需分多次请求,就能在单次请求内完成多个新学生与新课程的关联绑定。
3. 创建多层嵌套关联的新资源
比如创建一个新订单,同时创建对应的收货地址和账单地址,并将两个地址关联到订单:
{ "data": { "type": "orders", "lid": "temp-order-001", "attributes": { "total": 199.99 }, "relationships": { "shipping-address": { "data": { "type": "addresses", "lid": "temp-shipping-addr" } }, "billing-address": { "data": { "type": "addresses", "lid": "temp-billing-addr" } } } }, "included": [ { "type": "addresses", "lid": "temp-shipping-addr", "attributes": { "street": "XX路123号", "city": "上海" } }, { "type": "addresses", "lid": "temp-billing-addr", "attributes": { "street": "YY路456号", "city": "北京" } } ] }
这种场景下,lid允许客户端一次性构建完整的资源关联树,服务器能准确识别各个新建资源之间的层级关系。
内容的提问来源于stack exchange,提问作者jacquev6
相关产品推荐
相关产品推荐

