1

I am trying to create a one-to-many relation of the same type. In this case, a user can report to one user and in turn have many users reporting to them.

My data model currently looks like this:

type User {
  id: ID! @id
  name: String!
  email: String! @unique
  reportsTo: User @relation(name: "UserReports")
  reports: [User] @relation(name: "UserReports")
}

I expect adding a userId to reportsTo should add the corresponding user's ID to reports.

However, adding a userId to reportsTo is adding the userId to the same user's reports, rather than other users reports.

Jonny
  • 121
  • 1
  • 5

1 Answers1

0

You can't have a relationship with different elements of the one type. A relation is connecting two different types so we know they share information. Therefore we need to create some addition types that we can base a relationship on.

I've created two different types, one a "supervisor" who is a user who supervises other users, but we will have those users as a second type, "supervisee". Each user can be both a supervisor and a supervisee. There is a relation between a user and each of these two types and a relation between these two types as well.

This is the datamodel:

type User {
  id: ID! @id
  name: String!
  email: String! @unique
  supervisor: Supervisor @relation(name: "UserToSupervisor")
  supervisee: Supervisee @relation(name: "UserToSupervisee")
}

type Supervisor {
  id: ID! @id
  user: User! @relation(name: "UserToSupervisor")
  supervisees: [Supervisee!]! @relation(name: "SupervisorToSupervisee")
}

type Supervisee {
  id: ID! @id
  user: User! @relation(name: "UserToSupervisee")
  supervisor: Supervisor! @relation(name: "SupervisorToSupervisee")
}

You must view the "supervisor" field in user not as who that users supervior is, but that the user might be a supervisor themselves. This is also the case with supervisee. Basically supervisor and supervisee are extensions of user and the working relationship between them is defined between those two types.

Andrew1325
  • 3,519
  • 1
  • 14
  • 25