반응형
반응형

 

prisma/schema.prisma

model User {
  id    Int     @id @default(autoincrement()) // pk, autoincremnt속성
  email String  @unique // unique속성
  name  String? @db.VarChar(255)
  posts Post[] // 1:N 관계 설정
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false) // default값 설정
  author    User    @relation(fields: [authorId], references: [id]) // fields : fk키, references : 연결 테이블의 키
  authorId  Int
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

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

// .env file
// DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

프리즈마 모델 생성 및 DB Conneciton 생성

 

 

prisma 데이터 생성 (INSERT)

const prisma = new PrismaClient()

/** 단건 INSERT 예제1 **/
async function main() {
  const user = await prisma.user.create({
    data: {
      name: 'Alice',
      email: 'alice@prisma.io',
    },
  })
  console.log(user)
}

/** 단건 INSERT 예제2 **/
async function main() {
  const user = await prisma.user.create({
    data: {
      name: 'Bob',
      email: 'bob@prisma.io',
      posts: {
        create: {
          title: 'Hello World',
        },
      },
    },
  })
  console.log(user)
}

/** user, posts 테이블 데이터 INSERT **/
// 따로따로 데이터 INSERT할 수 있지만 연관관계가 있기 때문에 데이터 무결성 해결
const result = await prisma.user.create({
  data: {
    email: 'saanvi@prisma.io',
    posts: {
      createMany: {
        data: [{ title: 'My first post' }, { title: 'My second post' }],
      },
    },
  },
  include: {
    posts: true,
  },
})

// connect의 경우 이미 있는 데이터의 연관관계를 체크한 후에 있으면 데이터를 생성
const result = await prisma.user.create({
  data: {
    email: 'vlad@prisma.io',
    posts: {
      connect: [{ id: 8 }, { id: 9 }, { id: 10 }],
    },
  },
  include: {
    posts: true, // Include all posts in the returned object
  },
})

 

 

prisma 조회 (SELECT)

const prisma = new PrismaClient() // 프리즈마 객체 생성

/** user 테이블 전체 조회 **/
async function main() {
  const users = await prisma.user.findMany()
  console.log(users)
}

/** unique키 성질 조회**/
const getUser: User | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
})

/** 첫번째 결과값만 가져오기 **/
const user = await prisma.user.findFirst({
  include: {
    posts: true,
  },
})

/** 집계 조회 (갯수) **/
const relationCount = await prisma.user.findMany({
  include: {
    _count: {
      select: { posts: true },
    },
  },
})


/** 특정 필드 조회 + where절 **/
const getUser: object | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
  select: {
    email: true,
    name: true,
  },
})

/** 특정 필드 조회 Join **/
const users = await prisma.user.findMany({
  select: {
    name: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

/** user 테이블 Join 조회 **/
async function main() {
  const usersWithPosts = await prisma.user.findMany({
    include: {
      posts: true,
    },
  })
  console.dir(usersWithPosts, { depth: null })
}

/** OR, NOT 절 **/
const result = await prisma.user.findMany({
  where: {
    OR: [
      {
        email: {
          endsWith: 'prisma.io',
        },
      },
      { email: { endsWith: 'gmail.com' } },
    ],
    NOT: {
      email: {
        endsWith: 'hotmail.com',
      },
    },
  },
  select: {
    email: true,
  },
})

/** 포함 여부 **/
const firstQueryResults = await prisma.post.findMany({
  take: 4,
  where: {
    title: {
      contains: 'Prisma' /* Optional filter */,
    },
  },
  orderBy: {
    id: 'asc',
  },
})


/** 정렬 **/
const usersWithPosts = await prisma.user.findMany({
  orderBy: [
    {
      role: 'desc',
    },
    {
      name: 'desc',
    },
  ],
  include: {
    posts: {
      orderBy: {
        title: 'desc',
      },
      select: {
        title: true,
      },
    },
  },
})

/** 커서기반 **/
// 처음 조회
const firstQueryResults = await prisma.post.findMany({
  take: 4,
  where: {
    title: {
      contains: 'Prisma' /* Optional filter */,
    },
  },
  orderBy: {
    id: 'asc',
  },
})
const lastPostInResults = firstQueryResults[3] // Remember: zero-based index! :)
const myCursor = lastPostInResults.id // Example: 29

// 다음 조회
const secondQueryResults = await prisma.post.findMany({
  take: 4,
  skip: 1, // Skip the cursor
  cursor: {
    id: myCursor,
  },
  where: {
    title: {
      contains: 'Prisma' /* Optional filter */,
    },
  },
  orderBy: {
    id: 'asc',
  },
})


/** OFFSET, LIMIT **/
const results = await prisma.post.findMany({
  skip: 3, // offset
  take: 4, // limit
})

 

prisma 조회 (UPDATE)

/** 특정 조건 연관관계 레코드 단건 업데이트 **/
const result = await prisma.user.update({
  where: {
    id: 6,
  },
  data: {
    posts: {
      update: {
        where: {
          id: 9,
        },
        data: {
          title: 'My updated title',
        },
      },
    },
  },
  include: {
    posts: true,
  },
})


/** 특정 조건 연관관계 레코드 다건 업데이트 **/
const result = await prisma.user.update({
  where: {
    id: 6,
  },
  data: {
    posts: {
      updateMany: {
        where: {
          published: true,
        },
        data: {
          published: false,
        },
      },
    },
  },
  include: {
    posts: true,
  },
})

 

prisma 조회 (DELETE)

/** 관련 데이터 전체 삭제**/
const result = await prisma.user.update({
  where: {
    id: 11,
  },
  data: {
    posts: {
      deleteMany: {},
    },
  },
  include: {
    posts: true,
  },
})

/** 관련 데이터 조건 삭제**/
const result = await prisma.user.update({
  where: {
    id: 11,
  },
  data: {
    posts: {
      deleteMany: {
        published: false,
      },
    },
  },
  include: {
    posts: true,
  },
})

 

prisma CLI

"prebuild": "rimraf dist && npx prisma generate" // 기존 컴파일 삭제 및 prisma 객체 생성 (model 변경시 필수 실행 명령어)
"db-pull": "npx prisma db pull", // db 변경사항을 schema.prisma에 업데이트
"db-push": "npx prisma db push", // schema.prisma 변경사항을 db에 적용
반응형