如何在graphql突变中设置多对多关系? [英] how to set many-to-many relation in graphql mutation?
问题描述
我可能遗漏了一些东西,但在 Apollo 文档中找不到关于在创建新条目时设置多对多关系的方法的任何信息.
I may be missing something, but can not find any information on Apollo docs about the way to set a many-to-many relation when creating a new entry.
当关系是一对多时,就像在多侧对象中设置关系一侧的 ID 一样简单.
When the relation is one-to-many it is as simple as setting the ID of the one-side of the relationship in the many-side object.
但是让我们假设我正在与 Books 和 Authors 合作,我将如何编写一个为一个(或多个?)作者创建 Book 的 graphql 查询?
But let's pretend I am working with Books and Authors, how would I write a graphql query that creates a Book for one (or many?) Authors?
推荐答案
这可能应该发生在 GraphQL 服务器上的 API 层(即模式).对于多对多关系,您应该有一个联接"类型来表示 BookAuthor
多对多关系,然后向该联接类型添加一个条目.
This should probably happen at the API layer on the GraphQL server (i.e. schema). For many-to-many relationships, you should have a "join" type to denote the BookAuthor
many-to-many relationship, and then add an entry to that join type.
本质上,您将拥有一个名为 Book
的类型,另一个名为 Author
,最后还有一个名为 BookAuthor
.您可以添加一些突变来管理这种关系.也许...
Essentially then you'll have a type called Book
, another called Author
, and finally one more called BookAuthor
. And you can add a few mutations to be able to manage that relationship. Perhaps...
addToBookAuthorConnection
updateBookAuthorConnection
removeFromBookAuthorConnection
这是使用符合 Relay 规范的 API 的常规设置.您可以阅读有关如何为多对多构建 API 的更多信息这里的关系.
This is a conventional setup using a Relay-spec compliant API. You can read more about how to structure your API for many-to-many relationships here.
然后,您只需要从 Apollo 中调用 addToBookAuthorConnection
突变,即可添加到前端的多对多连接.
Then, you only need to call the addToBookAuthorConnection
mutation from Apollo instead to be able to add to that many-to-many connection on your frontend.
希望这会有所帮助!
这篇关于如何在graphql突变中设置多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!