You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多条件商品数据库查询:统一请求方案可行性咨询

问题描述

我需要从数据库中获取商品信息,有三类查询场景:

  • 按指定分类分页查询,每次返回12条;
  • 查询isBest=true的商品,返回9条;
  • 查询isNew=true且指定分类的商品,分5次每次返回3条。

这些查询对应不同页面,现在纠结用带参数的统一请求还是拆分多个独立请求,已经写了基于Prisma的统一请求代码,想咨询这个方案是否可行。目前数据库里只有1条商品,后续会补充更多数据。

现有实现代码
const {bring,isBest,isNew,page,category} = query; 
const condition:ConditionType={};
if(isBest) condition['isBest'] =isBest;
if(isNew) condition['isNew'] =isNew;
const products = await prismaHelper.product.findMany({
    orderBy: {
      order: 'desc',
    },
    take: bring,
    skip: bring * (parseInt((page as string) ?? 1) - 1),
    where: {
      category: {
        link: category[1],
      },
      AND: {
        isDeleted: false,
        isShow: true,
        ...condition
      },
    },
});
预期返回格式
{
  "products": [
    {
      "id": 1,
      "name": "something",
      ... 
    },
    ...
    {
      "id": 9,
      "name": "something",
      ... 
    }
  ]
}
方案可行性分析

你的统一请求方案完全可行,这种方式能减少后端路由数量、复用查询逻辑,后期维护成本更低。但现有代码存在几个细节问题,调整后才能适配所有场景:

  1. 分类参数强制依赖问题
    当前代码强制读取category[1],但场景2(仅查询isBest商品)不需要分类条件,会直接报错。建议增加判断,按需添加分类查询项:

    const whereConditions = {
      isDeleted: false,
      isShow: true,
      ...condition
    };
    if (category?.length > 1) {
      whereConditions['category'] = { link: category[1] };
    }
    
  2. 参数校验与默认值缺失

    • bring没有默认值,前端不传会导致分页计算异常,建议设置默认值:const bring = parseInt(query.bring) || 12;
    • page的类型转换要兼容非数字情况:const pageNum = parseInt(page as string) || 1;,避免NaN导致skip计算错误
    • isBest/isNew要做布尔值转换,前端可能传字符串"true",直接赋值会导致查询不匹配:if(isBest) condition['isBest'] = isBest === 'true' || isBest === true;
  3. AND条件写法冗余
    Prisma的where条件默认就是AND逻辑,不需要额外包裹AND对象,可简化为:

    where: {
      isDeleted: false,
      isShow: true,
      ...(category?.length > 1 ? { category: { link: category[1] } } : {}),
      ...condition
    }
    
  4. 场景3的分页适配
    场景3分5次每次返回3条,只要前端传bring=3和对应page=1~5,现有分页逻辑完全支持,无需额外修改。

调整后,这个统一接口就能完美覆盖所有三类查询需求。

内容的提问来源于stack exchange,提问作者Neia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:15:23