tomcajot
tomcajot

Reputation: 193

GraphQl One-Direction Relationship

I'd like my user to have a list of workouts (they can be active, completed, todo). Do I have to make a link from Workout to user in order to make this work? Is there no other way? Having a link back seems weird because I'd have a loop user>workout>user>workout...

I'm not sure if this is supposed to be done in graphql, I'm new to graphql. I currently have the following schema:

type User {
    email: String @unique
    fullName: String
    birthDate: Date
    weight: Int
    height: Int
    country: String
    trainingFrequency: Int
    trainingGoal: String
    isOnboarded: Boolean
    workouts: [Workout]
}

type Workout {
    name: String!
    state: State!
}

enum State {
  ACTIVE
  TODO
  COMPLETED
}

type Query {
    allUsers: [User!]!
    findUserByEmail(email: String!): User
}

Upvotes: 0

Views: 476

Answers (1)

ptpaterson
ptpaterson

Reputation: 9583

With Fauna, a two way relationship is always created for you when you use the @relation directive. In a one-to-many relationship a reference will be stored in all of the many-side Documents (Workout type in your case). Traversing the graph from the one-side (User type) to the many-side is made possible with an Index that is automatically generated for you.

Yes, you can query (nearly) infinitely cyclically, but in practice, there is no benefit to it.

Make sure you include the @relation directive.

type User {
    email: String @unique
    fullName: String
    birthDate: Date
    weight: Int
    height: Int
    country: String
    trainingFrequency: Int
    trainingGoal: String
    isOnboarded: Boolean
    workouts: [Workout] @relation
}

type Workout {
    name: String!
    state: State!
    owner: User! @relation
}

Upvotes: 1

Related Questions