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

React-Query + Prisma动态过滤:无需时如何省略过滤条件?

解决方案

前端处理:动态生成查询参数

前端通过条件判断,仅在有有效过滤值时才传递对应字段,避免无意义的空参数:

// 单过滤器场景:无过滤值时不传filters
const queryParams = colorFilter 
  ? { filters: { color: colorFilter } } 
  : {};

const { data, isLoading } = trpc.user.getAll.useQuery(queryParams);

如果后续新增多个过滤器(比如name过滤),可扩展为:

const filters = {};
if (colorFilter) filters.color = colorFilter;
if (nameFilter) filters.name = nameFilter;

// 仅当有过滤条件时才传递filters
const queryParams = Object.keys(filters).length > 0 ? { filters } : {};

const { data, isLoading } = trpc.user.getAll.useQuery(queryParams);

后端调整Zod校验规则

修改输入校验Schema,允许filters为可选对象,且内部过滤字段也设为可选,让前端不传或传部分字段都能通过校验:

getAll: t.procedure
  .input(z.object({
    filters: z.object({ 
      color: z.string().optional() 
    }).optional()
  }))
  // ...后续查询逻辑

动态构建Prisma查询条件

在查询函数中,仅将存在的过滤字段加入where对象,Prisma会自动忽略空对象或不存在的字段:

.query(({ ctx, input }) => {
  const where = {};
  // 仅当color过滤值存在时,才添加该条件
  if (input?.filters?.color) {
    where.color = input.filters.color;
  }
  // 新增其他过滤器时,直接追加判断即可
  // if (input?.filters?.name) {
  //   where.name = { contains: input.filters.name };
  // }

  return ctx.prisma.user.findMany({ where });
}),

多过滤器场景优化:抽离条件构建逻辑

如果后续有大量过滤字段,把构建where条件的逻辑抽成独立函数,保持代码整洁易维护:

// 抽离到工具函数或单独文件中
const buildUserFilterWhere = (filters) => {
  const where = {};
  if (filters?.color) where.color = filters.color;
  if (filters?.name) where.name = { contains: filters.name };
  if (filters?.age) where.age = { gte: filters.age };
  return where;
};

// 在TRPC过程中使用
getAll: t.procedure
  .input(z.object({
    filters: z.object({ 
      color: z.string().optional(),
      name: z.string().optional(),
      age: z.number().optional()
    }).optional()
  }))
  .query(({ ctx, input }) => {
    const where = buildUserFilterWhere(input?.filters);
    return ctx.prisma.user.findMany({ where });
  }),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:50:31