# Prisma API

# CURD 增删改查

# create 创建

创建一个记录

const user = await prisma.user.create({
  data: {
    email: 'elsa@prisma.io',
    name: 'Elsa Prisma',
  },
})

创建多个记录

const createMany = await prisma.user.createMany({
  data: [
    { name: 'Bob', email: 'bob@prisma.io' },
    { name: 'Bobo', email: 'bob@prisma.io' }, // Duplicate unique key!
    { name: 'Yewande', email: 'yewande@prisma.io' },
    { name: 'Angelique', email: 'angelique@prisma.io' },
  ],
  skipDuplicates: true, // Skip 'Bobo'
})

# read 查询

根据Id或者标识符

// By unique identifier
const user = await prisma.user.findUnique({
  where: {
    email: 'elsa@prisma.io',
  },
})

// By ID
const user = await prisma.user.findUnique({
  where: {
    id: 99,
  },
})

根据复合id或者复合键

model TimePeriod {
  year    Int
  quarter Int
  total   Decimal

  @@id([year, quarter])
}
const timePeriod = await prisma.timePeriod.findUnique({
  where: {
    year_quarter: {
      quarter: 4,
      year: 2020,
    },
  },
})

获取所有记录

const users = await prisma.user.findMany()

获取首个记录

const findUser = await prisma.user.findFirst({
  where: {
    posts: {
      some: {
        likes: {
          gt: 100
        }
      }
    }
  },
  orderBy: {
    id: "desc"
  }
})

按单个字段值过滤

const users = await prisma.user.findMany({
  where: {
    email: {
      endsWith: "prisma.io"
    }
  },
}

按多个字段值过滤

const users = await prisma.user.findMany({
  where: {
    OR: [
      {
        name: {
          startsWith: 'E',
        },
      },
      {
        AND: {
          profileViews: {
            gt: 0,
          },
          role: {
            equals: 'ADMIN',
          },
        },
      },
    ],
  },
})

按相关记录字段值过滤

const users = await prisma.user.findMany({
  where: {
    email: {
      endsWith: "prisma.io"
    },
    posts: {
      some: {
        published: false
      }
    }
  },
}

返回指定的字段

const user = await prisma.user.findUnique({
  where: {
    email: 'emma@prisma.io',
  },
  select: {
    email: true,
    name: true,
  },
})

存在关联查询时

const user = await prisma.user.findUnique({
  where: {
    email: 'emma@prisma.io',
  },
  select: {
    email: true,
    posts: {
      select: {
        likes: true,
      },
    },
  },
})

# update 更新

更新单条记录

const updateUser = await prisma.user.update({
  where: {
    email: 'viola@prisma.io',
  },
  data: {
    name: 'Viola the Magnificent',
  },
})

更新多条记录

const updateUsers = await prisma.user.updateMany({
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
  data: {
    role: 'ADMIN',
  },
})

更新或插入记录

const upsertUser = await prisma.user.upsert({
  where: {
    email: 'viola@prisma.io',
  },
  update: {
    name: 'Viola the Magnificent',
  },
  create: {
    email: 'viola@prisma.io',
    name: 'Viola the Magnificent',
  },
})

更新一个数字项

const updatePosts = await prisma.post.updateMany({
  data: {
    views: {
      increment: 1,
    },
    likes: {
      increment: 1,
    },
  },
})

# delete 删除

删除单个记录

const deleteUser = await prisma.user.delete({
  where: {
    email: 'bert@prisma.io',
  },
})

删除多条记录

const deleteUsers = await prisma.user.deleteMany({
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
})

删除所有记录

const deleteUsers = await prisma.user.deleteMany({})

删除有关联的表数据

两种方式:

  • 方式一:将关联关系设置为可选
  • 方式二:同时删除两个数据,使用事务确保一致性
const deletePosts = prisma.post.deleteMany({
  where: {
    authorId: 7,
  },
})

const deleteUser = prisma.user.delete({
  where: {
    id: 7,
  },
})

const transaction = await prisma.$transaction([deletePosts, deleteUser])

# 选择字段

默认情况下的查询会返回所有的字段,可以使用selectinclude API来指定需要返回的字段

// Returns an object or null
const getUser: object | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
  select: {
    email: true,
    name: true,
  },
})

查询有关联的表 使用 select

const users = await prisma.user.findMany({
  select: {
    name: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

查询有关联的表 使用 include

const users = await prisma.user.findMany({
  // Returns all user fields
  include: {
    posts: {
      select: {
        title: true,
      },
    },
  },
})

#

# 高级

# @map 和 @@map

使用@map@@map可以数据库的表名和字段名称

model Category {
  id                 Int                @id @default(autoincrement()) @map("category_id")
  name               String?            @db.VarChar(256)
  post_in_categories PostInCategories[]

  @@map("categories")
}

model PostInCategories {
  post_id     Int
  category_id Int
  categories  Category @relation(fields: [category_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
  posts       Post     @relation(fields: [post_id], references: [id], onDelete: NoAction, onUpdate: NoAction)

  @@unique([post_id, category_id], map: "post_id_category_id_unique")
  @@map("post_in_categories")
}

model Post {
  id                 Int                @id @default(autoincrement()) @map("post_id")
  created_at         DateTime?          @default(now()) @db.Timestamptz(6)
  title              String             @db.VarChar(256)
  content            String?
  author_id          Int?
  users              User?              @relation(fields: [author_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
  post_in_categories PostInCategories[]

  @@map("posts")
}

model Profile {
  id      Int     @id @default(autoincrement()) @map("profile_id")
  bio     String?
  user_id Int     @unique
  users   User    @relation(fields: [user_id], references: [id], onDelete: NoAction, onUpdate: NoAction)

  @@map("profiles")
}

model User {
  id       Int      @id @default(autoincrement()) @map("user_id")
  name     String?  @db.VarChar(256)
  email    String   @unique @db.VarChar(256)
  posts    Post[]
  profiles Profile?

  @@map("users")
}
陕ICP备20004732号-3