// prisma/schema.prisma generator client { provider = "prisma-client-js" } datasource db { provider = "sqlite" // 开发用 SQLite,上线改 "postgresql" url = env("DATABASE_URL") } model Product { id String @id @default(cuid()) // 自动生成唯一 ID name String description String? price Float imageUrl String? stock Int @default(0) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Order { id String @id @default(cuid()) userId String // 暂写死,以后接登录 total Float status String @default("pending") items OrderItem[] createdAt DateTime @default(now()) } model OrderItem { id String @id @default(cuid()) orderId String order Order @relation(fields: [orderId], references: [id]) productId String product Product @relation(fields: [productId], references: [id]) quantity Int price Float // 下单时价格快照 }
import { prisma } from '@/lib/prisma' // 查列表(支持分页、排序、条件) const products = await prisma.product.findMany({ where: { price: { gte: 100 } }, // WHERE price >= 100 orderBy: { createdAt: 'desc' }, skip: 0, take: 10, }) // 查单个 const product = await prisma.product.findUnique({ where: { id: 'xxx' } }) // 新增 const created = await prisma.product.create({ data: { name: '商品名', price: 99.9, stock: 100 } }) // 更新 const updated = await prisma.product.update({ where: { id: 'xxx' }, data: { price: 89.9 } }) // 删除 await prisma.product.delete({ where: { id: 'xxx' } }) // 关联查询(联表查订单 + 商品) const order = await prisma.order.findUnique({ where: { id: 'xxx' }, include: { items: { include: { product: true } } } })
| 命令 | 用途 | 说明 |
|---|---|---|
npx prisma db push | 同步模型到数据库 | 开发时用,直接改表结构 |
npx prisma studio | 打开浏览器数据管理 | 类似 Navicat,可视化查看数据 |
npx prisma generate | 重新生成客户端代码 | 改了 schema 后必须执行 |
npx prisma migrate dev | 生成带记录的迁移文件 | 生产环境用,可追溯版本 |