如何使用单个POST请求创建多个关联记录?

huangapple go评论84阅读模式
英文:

How do I create multiple associated records with a single POST request?

问题

这里的资源是一种日志类型,将创建5个不同的记录,其中包括天气、位置等等...它们都将共享关联。

据我了解,按照惯例,每个资源应该创建一个帖子,但如果这些资源需要其他记录的外键,我无法弄清楚如何跟踪与该日志相关的所有记录的ID。

目前,我正在发送创建所有资源所需的所有数据的单个请求,如果其中一个请求出错,将不会创建任何记录,因为我将使用事务。这是常规做法吗?

英文:

The resource here is a Log type that will create 5 different records, one for weather, location etc... they will all share associations.

It's my understanding that convention would be to create a post for each resource but if these resources require the foreign key of other records I can't figure out how I would keep track of all the id's of the records created relating to that log.

Right now I'm sending all the data needed to create all the resources in a single request and if one errors out none would be created as I would use a transaction. Is that convention?

答案1

得分: 1

“按照惯例,每个资源都应该创建一个帖子。”

当你有一个简单的模型,其中一个对象受到一个用户操作的影响时,这个惯例非常有效。这种模型非常常见,几乎在每本关于REST的书籍或文章中都有实现。

现实情况更加复杂,你的问题就是一个很好的例子。按表格创建公共API是一种已知且不幸广泛传播的反模式:

https://martinfowler.com/bliki/AnemicDomainModel.html

一般原则是,围绕你的业务问题构建解决方案,而不是围绕技术框架或模式。

“现在我正在发送创建所有资源所需的所有数据的单个请求。”

这听起来是一个很好的解决方案。一个业务操作 -> 一个API调用 -> 一个数据库事务。这很简单明了。如果没有必要,不要让它变得更加复杂。

英文:

> convention would be to create a post for each resource

This convention works great when you have a simple model when one object is affected by one user action. That model is quite common and implemented in every REST book/article.

Reality is more complicated, and your question is a great example of that.
Implementing PUBLIC API per table is known and unfortunately widely spread antipattern:

https://martinfowler.com/bliki/AnemicDomainModel.html

Rule of thumb, build your solution around your business problem, not around a technical framework or pattern.

> Right now I'm sending all the data needed to create all the resources
> in a single request

That sounds like a great solution. One business action -> one API call -> one DB transaction. It is nice and simple. Do not make it more complicated if it is not necessary.

huangapple
  • 本文由 发表于 2022年7月11日 17:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/72936337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定