How to model schema if we have many to many relationship between multiple models/entities?

Dgraph does not currently support the concept of unique across multiple types. There are a few different ways to accomplish the use case:

get the list of groups for User + Company combinations

Option 1, with a map type:

This would create a new type to handle this relationship as a node. An edge can only link between two nodes, so when a link is needed between more than two nodes then a type is needed.

type UserGroupMap {
  user: User
  company: Company
  group: Group
}

Then you can do a query with cascade to get the group of any specific user/company combination

query ($user: uid! $company: uid!) {
  groups(func: (type(UserGroupMap))) @cascade {
    user @filter(eq(uid,$user))
    company @filter(eq(code,$company))
    group {
      uid
    }
  }
}

Option 2, with edges between group to companies and users.

Thinking about the use case leads me to believe that the Groups are related to the Users and Companies. This would enable a form of access control of the group depending on the User and the Company.

type Group {
  users: [User]
  companies: [Company]
}

In this schema you would not need to query the map, but rather just the Group itself.

h/t to @amaster507. Very many thanks.

2 Likes