Search code examples
prismaplanetscale

Prisma, how to preserve foreign data?


It's been a few months since I started prisma and I'm still confused.

In a normal database, foreign key data also exists in table data. However, according to the prisma document, in prisma, the data does not exist at the database level.

So where is it stored? It seems that the things I do "connect:id:1" are stored in the Prisma client. If I delete the prisma dependency and install it again with npm install, will all these relational data be deleted too?? How can I make it as safe as possible????

And it seems too dangerous when I migrate later. what am I misunderstanding?


ADDED

const user = await prisma.user.create({
  data: {
    email: '[email protected]',
    posts: {
      connect: [{ id: 8 }, { id: 9 }, { id: 10 }],
    },
  },
  include: {
    posts: true, // Include all posts in the returned object
  },
})

in this case, id 8, id 9, id 10, Where are all these stored? Is there any way to check other than prisma studio or select query? I don't know where it is physically stored. It's not even in the planet scale database.

// In the workbench, the foriegn key is actually saved and can be exported. I don't know how it's not at the database level, but where it is referenced and stored.


Solution

  • Considering this Schema:

    generator client {
      provider        = "prisma-client-js"
    }
    
    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    model User {
      id    Int    @id @default(autoincrement())
      name  String
      email String @unique
      posts Post[]
    }
    
    model Post {
      id        Int     @id @default(autoincrement())
      title     String
      published Boolean @default(true)
      author    User    @relation(fields: [authorId], references: [id])
      authorId  Int
    }
    

    There is a one-to-many relationship between User and Posts.

    according to the prisma document, in prisma, the data does not exist at the database level.

    Only the relation fields do not exist at the database level, so in this case posts in User model and author in Post model would not exist at database level. But the foreign key exists at the database level, so in this case authorId is actually stored in the database.

    Based on the create query you have shared:

    in this case, id 8, id 9, id 10, Where are all these stored?

    The connect statement in create query is essentially linking the records. So to elaborate Posts with id 8,9,10 would have the authorId value of the new user record which is created.

    So the data is stored in database, you can always check which posts are created by a specific author. You just need to query all the posts which has authorId set to the id which you are querying for.

    enter image description here