Prisma 多个可选排序属性,orderBy

问题描述 投票:0回答:2

我正在 Prisma 后端开发一个 GET 端点来检索所有任务。

目前,我想使用

sortBy

添加多个排序选项

在我下面的代码中有两个 sortBy 选项。但是,我似乎无法使它们都工作,只能使

orderBy[]
数组中的第一个对象工作。

router.get("/tasks", async (req, res) => {
  var currentPage = req.query.page || 1;
  const listPerPage = 45;
  const offset = (currentPage - 1) * listPerPage;

  var category = req.query.category;
  var sortQuery = req.query.sort;
  var sort = sortQuery.split("_");

  var idSortBy = "asc";
  var dateSortBy = "asc";

  if (sort !== undefined) {
    if (sort[0] === "id") {
      idSortBy = sort[1];
    } else {
      dateSortBy = sort[1];
    }
  }

  const allTasks = await prisma.task.findMany({
    orderBy: [
      {
        createdAt: dateSortBy,
      },
      {
        id: idSortBy,
      },
    ],
    where: { category: category },
    skip: offset,
    take: listPerPage,
  });

  res.json({
    data: allTasks,
    meta: { page: currentPage },
  });
});
sorting sql-order-by prisma
2个回答
0
投票

我找到了将所有排序选项解析为 findMany 函数中的 orderBy 的解决方案。

router.get("/tasks", async (req, res) => {
  var currentPage = req.query.page || 1;
  const listPerPage = 45;
  var offset = (currentPage - 1) * listPerPage;

  var category = req.query.category;

  var sort = req.query.sort.split("_");
  var orderByObject = {};
  orderByObject[sort[0]] = sort[1];
  var orderBySet = [orderByObject];

  const allTasks = await prisma.task.findMany({
    where: { category: category },
    skip: offset,
    take: listPerPage,
    orderBy: orderBySet,
  });

  res.json({
    data: allTasks,
    meta: { page: currentPage },
  });
});

0
投票

我想你想要这样的功能,重点是排序:

export const GET = async (req: NextRequest) => {
  try {
    // pagination
    const page = parseInt(req.nextUrl.searchParams.get("page") ?? "1")
    const limit = parseInt(req.nextUrl.searchParams.get("limit") ?? "20")
    const skip = (page - 1) * limit

    // search product
    const query = req.nextUrl.searchParams.get("search")
    const decodeQuery = query?.replace(/-/g, " ")

    // get total product
    const totalProducts = await prisma.product.count()

    // sortBy -> feature(descending/desc), price(high to low), price(low to high), A - Z, Z - A
    const sortBy = req.nextUrl.searchParams.get("sortBy")
    let orderBy = {}
    switch (sortBy) {
      case "feature":
        orderBy = { createdAt: "desc" }
        break
      case "price-high-to-low":
        orderBy = { price: "desc" }
        break
      case "price-low-to-high":
        orderBy = { price: "asc" }
        break
      case "a-z":
        orderBy = { title: "asc" }
        break
      case "z-a":
        orderBy = { title: "desc" }
        break
      default:
        orderBy = { createdAt: "desc" }
    }

    // category -> keyboard, deskmat, keycaps, coiled cable, mouse, switch, sticker, barebone
    const categories = req.nextUrl.searchParams.get("categories")

    const products = await prisma.product.findMany({
      where: {
        title: {
          contains: decodeQuery,
          mode: "insensitive",
        },
      },
      include: {
        images: true,
        categories: true,
        comments: {
          orderBy: {
            createdAt: "desc",
          },
        },
      },
      orderBy,
      skip: skip,
      take: limit,
    })

    if (decodeQuery) {
      return NextResponse.json({
        message: "data pencarian berhasil di ambil",
        products,
        currentPage: page,
        totalPages: Math.ceil(products.length / limit),
        totalProducts: products.length,
        status: 200,
      })
    }

    if (products.length > 0) {
      return NextResponse.json({
        message: "data berhasil di ambil",
        products,
        currentPage: page,
        totalPages: Math.ceil(totalProducts / limit),
        totalItems: products.length,
        totalProducts,
        status: 200,
      })
    }

    return NextResponse.json({
      message: "data not found",
      status: 404,
    })
  } catch (error) {
    console.log(error)
    return NextResponse.json({
      message: "internal server error",
      error: error,
      status: 500,
    })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.