GraphQL set or remove a relationship

Taking the documentation at https://dgraph.io/docs/graphql/mutations/update/
as the base.

Lets assume I added Posts and Authors from an external resource into DGraph, yet did not establish their relationship during the eg. bulk insert.

So I assume I have to Update Authors to set a relationship to Posts. How can I update an author and establish a relationship to a post, when I know the authors id and

  • the ids of the posts the relationship should be established with? Can I establish multiple relationships in one single update mutation, eg. if I know that author 0x1234 shall be assigned posts identified by ids 0x20 and 0x40
  • a search criteria for a post title (which matches more but one post) which shall be assigned to author 0x1234?

How will I be able to remove a relationship?

  • say I would like to remove the relationship from author identified by id to post identified with id
  • say I would like to remove the relationship from author identified by name to posts matching title

Thank you for help.

1 Like

Welcome back!

I’m gonna copy paste the schema here to make things more easy for me to read :

type Author {
	id: ID!
	name: String! @search(by: [hash])
	dob: DateTime
	posts: [Post]
}

type Post {
	postID: ID!
	title: String! @search(by: [term, fulltext])
	text: String @search(by: [fulltext, term])
	datePublished: DateTime
}

To Add a Relationship When You Know The IDs

mutation  {
  updateAuthor(patch: {filter : {authorID: "0x1234"}, set: {posts: ["0x20", "0x40"] } }) {
    numUids
  }
}

You will need a query to find the post ID of the post, then do the above mutation.

How will I be able to remove a relationship?

You can use the delete mutation if you have the IDs. I’ll leave it as an exercise to the reader.

An update mutation can use any searchable fields, not only the ID. So you could do an updatePost mutation with the filter matching your titles and then setting an author edge. But… Right now in the schema example above, there is no Post.author edge with a linking @hasInverse directive. I would set that up before creating any edges.

1 Like

@chewxy Thank you for your reply.

TODO. BRB.

means it’s something you have to figure our or is not yet implemented? I found
https://docs.fauna.com/fauna/current/api/graphql/relations#disconnect
where an explicit disconnect mutation is supported. I wonder if I have currently resort to DQL?

Oh, right. I had another pressing matter in real life when I was writing that response.

But you can use the delete mutations if you know the IDs. I’ll leave that as an exercise to the reader.

Thank you, I was not aware of that, indeed it works perfectly! I added where sensible @hasInverse. BTW. the expected parameter for an update mutation is input not patch. Patch is the mostly used variable name when using variable style.