I have a lot of trouble figuring out the 1 to 1 an...
# orm-help
c
I have a lot of trouble figuring out the 1 to 1 and 1 to many relation i made this schema then I have my graphql derived from that
Copy code
prisma
// This is your Prisma schema file,
// learn more about it in the docs: <https://pris.ly/d/prisma-schema>

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

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

model Games {
  id         Int      @id @default(autoincrement())
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
  short_hand String   @unique @db.VarChar(255)
  name       String   @unique @db.VarChar(255)
  in_boxes   Box[]
  set        Sets[]
}

model User {
  id         Int      @id @default(autoincrement())
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
  username   String   @unique @db.VarChar(255)
  password   String   @db.VarChar(255)
  role       Role     @default(USER)
  first_name String?  @db.VarChar(255)
  last_name  String?  @db.VarChar(255)
  store      String?  @db.VarChar(255)
  boxes      Box[]

}

model Store {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  name      String   @unique @db.VarChar(255)
}

model Box {
  id                Int      @id @default(autoincrement())
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt
  box_number        String   @db.VarChar(100)
  box_second_number String?   @db.VarChar(100)
  set               String   @db.VarChar(255)
  set_list          Sets     @relation(fields: [set], references: [name])
  gameid            Int?     @default(1)
  game              Games?   @relation(fields: [gameid], references: [id])
  User              User?    @relation(fields: [userId], references: [id])
  userId            Int?
}

model Sets {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  name      String   @unique @db.VarChar(255)
  code      String   @unique @db.VarChar(255)
  children  String[]
  in_boxes  Box[]
  game      String?  @db.VarChar(255)
  gamerel   Games?   @relation(fields: [game], references: [short_hand])
  edition   String?
}

enum Role {
  USER
  ADMIN
  CHRIS
}
Basically a user will have boxes that they own ( The boxes has a Game Type and contains a parent Set which Has it own set code and contain set children (array) The game type it self has only name and shortcode My main issue is that when I try to create a set with the resolver code
Copy code
graphql
//the graphql
mutation {
	  createBox (input:{box_number:"001", secondary_number:"A", game:{name:"yu"}, set:"Crucibile of War Unlimit"}) {
	    box_number
	    set
	    game
	    id
	  }
}
`
the resolver
Copy code
ts
   createBox: async (_: any, { input }: any, context: Context) => {
      const find = await context.prisma.games.findFirst({
        where: {name: {contains:input.game[0].name,
        mode:"insensitive"}}
        }
      );
      console.log(find);
      console.log(input.set);
      return await context.prisma.box.create({
        data: {

          box_number: input.box_number,
          box_second_number: input.secondary_number,
          gameid: find?.id,
          set: {connect: {
              name: input.set
            },
          },

            },

 

      });
    },
I get
Copy code
75 return await context.prisma.box.create(",
            "  Foreign key constraint failed on the field: `Box_set_fkey (index)`",
            "    at cb
I'm really confused on how to make it work
r
@Christophe Rudyj 👋 I had answered this on StackOverflow, did you get time to check that out? https://stackoverflow.com/questions/69756112/
c
Sorry I didnt have a notification from Stack Overflow i just saw it i'll test it right away
👍 1
Copy code
"→  83 return await context.prisma.box.create(",
            "  Foreign key constraint failed on the field: `Box_set_fkey (index)`",
            "    at cb (/home/kip/site/prisma_tut/node_modules/@prisma/client/runtime/index.js:38537:17)",
            "    at async Object.createBox (/home/kip/site/prisma_tut/src/schema/resolvers.ts:83:14)"
r
Is the
set
with that name present?
If you try to connect to a
set
that isn’t present, you will get this error.
c
I readded the set with that name in the db however how can i make it if theres no set create it or throw an error?
r
What you need is `connectOrCreate`:
Copy code
await prisma.box.create({
    data: {
      box_number: input.box_number,
      box_second_number: input.secondary_number,
      game: { connect: { id: find?.id } },
      set_list: {
        connectOrCreate: {
          where: { name: input.set },
          create: {
            code: 'code',
            name: input.set,
          },
        },
      },
    },
  })
c
so if i understand correctly the connector create must be made on the Prisma relation key not in my case set
r
Yes, the
set
field directly accepts the foreign key. You need to use the virtual field
set_list
to perform this operation.
c
Thank you so much it helped so much
Hi sorry but I ran into an other snag with my update function again foreign key error
Copy code
updateBox: async (_: any, { input}: any, context: Context) => {
      const findGame = await context.prisma.games.findFirst({
        where: {name: {contains:input.game[0].name,
        mode:"insensitive"}}
        }
      );
      const find = await context.prisma.box.update({
        where: {
          id: parseInt(input.id)
        },
        data: {
          box_number: input.box_number,
          box_second_number: input.box_second_number,
          gameid: findGame?.id,
       
          set_list: {
                name: input.set,
                gamerel: { connect: { id: findGame?.id } }
              },
          },

        
      });
      return find;
r
Only add the connect on
gamerel
if
findGame?.id
is not undefined, otherwise it will throw an error. A ternary operator check would work fine.
c
i got this error for some reason :
Copy code
SError: ⨯ Unable to compile TypeScript:
src/schema/resolvers.ts:182:17 - error TS2322: Type '{ name: any; gameFound: (id: any) => "" | { gamerel: { connect: { id: number | undefined; }; }; }; }' is not assignable to type 'SetsUpdateOneRequiredWithoutIn_boxesInput'.
  Object literal may only specify known properties, and 'name' does not exist in type 'SetsUpdateOneRequiredWithoutIn_boxesInput'.
r
Instead of
gameid
pass it via connect:
game: { connect: { id: 'some-id' } }
c
still the same error with this
Copy code
updateBox: async (_: any, { input}: any, context: Context) => {
      const findGame = await context.prisma.games.findFirst({
        where: {name: {contains:input.game[0].name,
        mode:"insensitive"}}
        }
      );
      // const gameFound = () => {
      //   if (typeof findGame?.id !== "undefined") {
      //     return {gamerel: { connect: { id: findGame?.id } }}
      //   } else {return "";}
      // }
      // console.log(typeof findGame?.id);
      const find = await context.prisma.box.update({
        where: {
          id: parseInt(input.id)
        },
        data: {
          box_number: input.box_number,
          box_second_number: input.box_second_number,
          game: {connect:{
            id: findGame?.id
          }}
       
          set_list: {

                name: input.set,
                gamerel: { connect: { id: findGame?.id}}
              },
          },

        
      });
      return find;
    },