andfilterwhere参数如何使用?

99ANYc3cd6
预计阅读时长 21 分钟
位置: 首页 参数 正文

这个参数通常出现在后端框架(如 NestJS, TypeORM, Sequelize, Prisma 等)的查询构建器(Query Builder)或服务层中,它的核心作用是组合多个 WHERE 条件,并且这些条件之间是“与”(AND)的逻辑关系

andfilterwhere 参数
(图片来源网络,侵删)

andFilterWhere 就是一个对象,它定义了查询时必须同时满足的所有过滤条件。


核心概念:AND 逻辑

andFilterWhere 的精髓在于 AND,当你使用它时,意味着数据库返回的每一行记录都必须满足 andFilterWhere 对象中定义的所有条件。

逻辑表达式: WHERE (条件1) AND (条件2) AND (条件3) ...

示例: 假设 andFilterWhere{ status: 'active', age: { gt: 18 } },那么它会被翻译成如下的 SQL 查询:

andfilterwhere 参数
(图片来源网络,侵删)
SELECT * FROM "users" WHERE "status" = 'active' AND "age" > 18;

只有那些 status 字段是 'active' 并且 age 字段大于 18 的用户记录才会被返回。


andFilterWhere 的结构

andFilterWhere 的结构通常是嵌套的对象,具体格式取决于你使用的框架,但其基本思想是相似的。

基本结构

一个最简单的 andFilterWhere 就是一个键值对对象:

// TypeScript 示例
interface AndFilterWhere {
  [key: string]: any; // key 是字段名,value 是条件值
}
const andFilterWhere: AndFilterWhere = {
  isDeleted: false,        // 条件1: isDeleted 字段必须为 false
  role: 'user',            // 条件2: role 字段必须为 'user'
};

高级结构:支持复杂操作符

为了支持“大于”、“小于”、“包含”等更复杂的查询,andFilterWhere 的值通常可以是一个对象,里面包含操作符。

andfilterwhere 参数
(图片来源网络,侵删)

常见操作符:

操作符 含义 示例 生成的 SQL 片段
eq 等于 (equal) { name: { eq: 'John' } } name = 'John'
ne 不等于 (not equal) { name: { ne: 'John' } } name <> 'John'
gt 大于 (greater than) { age: { gt: 18 } } age > 18
gte 大于等于 (greater than or equal) { age: { gte: 18 } } age >= 18
lt 小于 (less than) { age: { lt: 65 } } age < 65
lte 小于等于 (less than or equal) { age: { lte: 65 } } age <= 65
in 在...之中 (in) { city: { in: ['Beijing', 'Shanghai'] } } city IN ('Beijing', 'Shanghai')
notIn 不在...之中 (not in) { city: { notIn: ['Beijing', 'Shanghai'] } } city NOT IN ('Beijing', 'Shanghai')
like 模糊匹配 (like) { email: { like: '%@example.com' } } email LIKE '%@example.com'
iLike 不区分大小写的模糊匹配 (case-insensitive like) { name: { iLike: 'john' } } name ILIKE 'john' (PostgreSQL)

组合示例:

const andFilterWhere = {
  status: { eq: 'active' }, // 必须是 active 状态
  createdAt: { gte: '2025-01-01' }, // 并且创建时间在 2025-01-01 之后
  age: { gt: 18 },             // 并且年龄大于 18
};

对应的 SQL:

WHERE status = 'active' AND "createdAt" >= '2025-01-01' AND age > 18

在实际框架中的使用示例

andFilterWhere 通常作为 DTO (Data Transfer Object) 或 Service 方法的一部分,用于接收前端的查询参数。

示例 1: NestJS + TypeORM

假设我们有一个 UserService,它根据前端传来的查询条件来查找用户。

创建 DTO (数据传输对象) src/users/dto/find-user.dto.ts

import { IsOptional, IsString, IsNumber, IsEnum } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
export enum UserStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
}
export class FindUserDto {
  @ApiPropertyOptional({ description: '用户名' })
  @IsOptional()
  @IsString()
  username?: string;
  @ApiPropertyOptional({ description: '用户状态', enum: UserStatus })
  @IsOptional()
  @IsEnum(UserStatus)
  status?: UserStatus;
  @ApiPropertyOptional({ description: '最小年龄' })
  @IsOptional()
  @Transform(({ value }) => parseInt(value, 10))
  @IsNumber()
  minAge?: number;
}

在 Service 中使用 andFilterWhere src/users/users.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { FindUserDto } from './dto/find-user.dto';
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}
  async findAll(findUserDto: FindUserDto): Promise<User[]> {
    // 1. 构建一个空的 where 对象
    const where: any = {};
    // 2. 根据 DTO 动态构建 where 条件 (这就是 andFilterWhere 的核心逻辑)
    if (findUserDto.username) {
      where.username = findUserDto.username;
    }
    if (findUserDto.status) {
      where.status = findUserDto.status;
    }
    if (findUserDto.minAge) {
      where.age = { gte: findUserDto.minAge }; // 使用 gte 操作符
    }
    // 3. 将构建好的 where 对象传递给 find 方法
    // TypeORM 会自动将这些条件用 AND 连接起来
    return this.usersRepository.find({ where });
  }
}

当调用 GET /users?status=active&minAge=20 时,where 对象会变成:

{
  status: 'active',
  age: { gte: 20 }
}

TypeORM 最终会生成类似下面的 SQL:

SELECT * FROM "user" WHERE "status" = 'active' AND "age" >= 20

示例 2: Prisma (Prisma Query API)

Prisma 的查询语法更加直观,其 AND 逻辑体现在参数的结构上。

// prisma-client-lib/index.d.ts (或你的 Prisma Client 类型定义)
import { Prisma } from '@prisma/client';
async function findUsers(filters: { status?: string; minAge?: number }) {
  const where: Prisma.UserWhereInput = {};
  if (filters.status) {
    where.status = filters.status;
  }
  if (filters.minAge) {
    where.age = { gte: filters.minAge };
  }
  // where 对象有属性,Prisma 会自动用 AND 连接
  return prisma.user.findMany({
    where: where, // 或者直接写 where: { status: 'active', age: { gte: 20 } }
  });
}
// 调用
findUsers({ status: 'active', minAge: 20 });

Prisma 生成的 SQL 与上面 TypeORM 的例子完全相同。


orFilterWhere 的区别

理解 andFilterWhere 最好的方式就是和它的“兄弟” orFilterWhere (或 orWhere) 进行对比。

特性 andFilterWhere (AND) orFilterWhere (OR)
逻辑关系 必须同时满足所有条件 只需满足其中任意一个条件
SQL 翻译 WHERE cond1 AND cond2 AND cond3 WHERE (cond1 OR cond2 OR cond3)
使用场景 精确筛选,范围缩小 宽松筛选,范围扩大
示例 查找“”是管理员注册时间在今年的用户 查找“”是管理员是VIP用户的列表

andFilterWhere 是一个在服务层构建复杂查询的强大工具,它的关键点在于:

  1. 核心作用:定义一组必须同时满足的过滤条件。
  2. 数据结构:通常是一个嵌套的对象,键是字段名,值可以是具体值或包含操作符(如 gt, like)的对象。
  3. 动态构建:它不是写死的,而是根据前端传入的参数动态组装的,是实现灵活 API 查询的关键。
  4. OR 的区别AND 是“全都要”,OR 是“有一个就行”。

掌握了 andFilterWhere,你就能轻松实现功能强大且灵活的后端数据筛选功能。

-- 展开阅读全文 --
头像
戴尔Precision 7530拆机有哪些关键步骤和注意事项?
« 上一篇 今天
Acer Aspire 4250拆机步骤和注意事项有哪些?
下一篇 » 今天

相关文章

取消
微信二维码
支付宝二维码

最近发表

标签列表

目录[+]