如何在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.
但是,假装我正在与书籍和作者"一起工作,我该如何编写一个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
addToBookAuthorConnection
updateBookAuthorConnection
removeFromBookAuthorConnection
这是使用符合中继规范的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屋!