Redon

一心的小屋

Prisma 查询方法

发布于 # Prisma

Prisma Site

Prisma Playground

findUnique

const result = await prisma.user.findUnique({
  where: {
    email: "alice@prisma.io",
  },
});

findFirst

// 获取 title 字段以 A test 开头的第一个 Post 记录,并反转列表(take)
async function main() {
  const a = await prisma.post.create({
    data: {
      title: "A test 1",
    },
  });

  const b = await prisma.post.create({
    data: {
      title: "A test 2",
    },
  });

  const c = await prisma.post.findFirst({
    where: {
      title: {
        startsWith: "A test",
      },
    },
    orderBy: {
      title: "asc",
    },
    take: -1, // 反转列表
  });
}

findMany

const user = await prisma.user.findMany({
  where: { name: "Alice" },
});

create

const user = await prisma.user.findMany({
  where: { name: "Alice" },
});
const user = await prisma.user.create({
  data: { email: "alice@prisma.io" },
});

update

const user = await prisma.user.update({
  where: { id: 1 },
  data: { email: "alice@prisma.io" },
});

upsert

// 更新(如果存在)或创建一条 email 为 alice@prisma.io 的 User 记录

const user = await prisma.user.upsert({
  where: { id: 1 },
  update: { email: "alice@prisma.io" },
  create: { email: "alice@prisma.io" },
});

delete

const user = await prisma.user.delete({
  where: { id: 1 },
});

deleteMany

// 删除所有 name 为 Alice 的 User 记录
const deletedUserCount = await prisma.user.deleteMany({
  where: { name: "Alice" },
});

// 删除所有User
const deletedUserCount = await prisma.user.deleteMany({});

createMany

const users = await prisma.user.createMany({
  data: [
    { name: "Sonali", email: "sonali@prisma.io" },
    { name: "Alex", email: "alex@prisma.io" },
  ],
});

updateMany

const updatedUserCount = await prisma.user.updateMany({
  where: { name: "Alice" },
  data: { name: "ALICE" },
});

count

// 查询所有记录总数,查询 name 字段非空的总数,查询 city 字段非空的总数
const c = await prisma.user.count({
  select: {
    _all: true,
    city: true,
    name: true,
  },
});

aggregate

// 返回所有 User 记录的 profileViews 的 _min、_max 和 _count
const minMaxAge = await prisma.user.aggregata({
  _count: {
    _all: true,
  },
  _max: {
    profileViews: true,
  },
  _min: {
    profileViews: true,
  },
});

groupBy

// 按平均 profileViews 大于 200 的 country/city 分组,并返回每组 profileViews 的 _sum
const groupUsers = await prisma.user.groupBy({
  by: ["country", "city"],
  _count: {
    _all: true,
    city: true,
  },
  _sum: {
    profileViews: true,
  },
  orderBy: {
    country: "desc",
  },
  having: {
    profileViews: {
      _avg: {
        gt: 200,
      },
    },
  },
});