I have a Post
type than has a tag
field which can be associated with many Tag
entries (man-to-many relationship). The issue I am running into is when updating a Post
- I need to both create and associate new Tag
's for tags that do not yet exist, while preserving the existing Post
->Tag
relationships. Basically, what I am looking for is something akin to an upsert
when issuing a mutation update on a nested one-to-many field.
Here is my schema:
type Post @model {
createdAt: DateTime!
createdBy: User @relation(name: "PostsByUser")
description: String @defaultValue(value: "''")
id: ID! @isUnique
tags: [Tag!]! @relation(name: "TagsOfPost")
...
}
type Tag @model {
id: ID! @isUnique
tag: String!
createdBy: User @relation(name: "TagsByUser")
createdAt: DateTime!
posts: [Post!]! @relation(name: "TagsOfPost")
}
This mutation works to update a Post
and add new tags, but overwrite all of the existing values in the Post
's tag
field:
mutation updatePost(
$id: ID!
$createdById: ID!
$timestamp: DateTime!
$description: String
$tags: [PosttagsTag!]!
) {
updatePost(
id: $id
createdById: $createdById
timestamp: $timestamp
description: $description
tags: $tags
) {
id
timestamp
description
tags {
id
tag
}
createdBy {
id
username
}
}
}
I came across this post by @marktani but it's not clear how to implement the combined method he outlines:
Combined You can also use tags and tagsIds in the same mutation, this would connect the new Tutorial node to all the tags in tagsIds and connect it to the new tags in tags. This is what you want to do if you want to only allow tags with a unique text, so for a new Tutorial, there will likely be some tags that already exists, and some that need to be created.
Is it currently impossible to do this with one mutation? Would a second mutation be required after updating the post with new tags to re-establish the associations between the Post
and existing Tag
ids, i.e., having to repeatedly call addToTagsOfPost(tagsTagId: ID!
postsPostId: ID!)
? Thanks!