3

I am working on a workout app using Graphql Prisma and Postgres as my backend. So far my prisma schema is as follows:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Exercise {
  id        Int      @id @default(autoincrement())
  name      String
  numSets   Int
  holdTime  Int?
  owner     Workout? @relation(fields: [workoutId], references: [id])
  workoutId Int?
}

model Workout {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  category  String   
  exercises Exercise[]
}

The schema defines a Workout object that takes in a category and a list of Exercises. I am trying to create a workout with a list of objects using Prisma's nested create query however the list of exercises is not created. I can't tell if there is something wrong with my schema or my script.

The script that I am using to test out the create is:

const { PrismaClient } = require("@prisma/client")

const prisma = new PrismaClient()

async function main() {
    const newWorkout = await prisma.workout.create({
        data: {
            category: 'Push',
            exercises: {
              create: [
                {
                  name: "pushup",
                  numSets: 5
                },
                {
                  name: "headstand",
                  numSets: 3,
                  holdTime: 30
                }
              ]
            }
        }
    })
    console.log(newWorkout)

    const workout = await prisma.workout.findUnique({
      where: {
        id: 1
      }
    })
    console.log(workout.exercises)
}

main()
    .catch(e => {
        throw e
    })
    .finally(async () => {
        await prisma.$disconnect()
    })

Output from print statements:

console.log(newWorkout): "{ id: 1, createdAt: 2021-11-09T07:03:40.844Z, updatedAt: 2021-11-09T07:03:40.848Z, category: 'Push' }"

console.log(workout.exercises): "undefined"

1 Answer 1

2

Prisma does not fetch relation fields by default. As a result, the exercises field is not returned with the workout record. This applies to all queries, including the create and find.

To fetch the exercises field, you should use either include or select. include is preferred if you want to return all the fields in the relation, whereas select lets you specify exact fields to return.

Here is the updated version of your code that returns the excercises field:

const newWorkout = await prisma.workout.create({
        data: {
            category: 'Push',
            exercises: {
              create: [
                {
                  name: "pushup",
                  numSets: 5
                },
                {
                  name: "headstand",
                  numSets: 3,
                  holdTime: 30
                }
              ]
            }
        },
        include: {
            exercises: true
        }
    })

    console.log(newWorkout) 

    let workout = await prisma.workout.findUnique({
      where: {
        id: 1
      },
      include: {
          exercises: true
      }
    })
    console.log(workout.exercises) 

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you using the include works and is exactly what I needed!
Awesome! Happy to help :)
Have been looking into this for quiet some time, this answer helped thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.