NestJS 中使用 TypeORM 查询包含指定分类的书籍实体

4次阅读

NestJS 中使用 TypeORM 查询包含指定分类的书籍实体

本文介绍如何在 Nestjs 中基于 TypeORM 的 QueryBuilder 实现按数组字段(如 category: String[])精确匹配筛选,解决 simple-Array 类型字段的模糊/包含式查询问题,并提供可复用、类型安全的分页查询方案。

本文介绍如何在 nestjs 中基于 typeorm 的 querybuilder 实现按数组字段(如 `category: string[]`)精确匹配筛选,解决 `simple-array` 类型字段的模糊/包含式查询问题,并提供可复用、类型安全的分页查询方案。

在 NestJS 项目中,当实体字段使用 @column({ type: “simple-array” })(如 category: string[])时,TypeORM 会将其序列化为数据库中的字符串(例如 “{test1,test2,test3}” 或 [“test1″,”test2″,”test3”],具体取决于数据库和配置)。直接使用 IN 操作符无法正确匹配——因为数据库中存储的是完整 json 字符串或 CSV 格式,而非独立行值。

因此,不能简单写 WHERE category IN (‘test2’)。正确做法是利用数据库的字符串包含函数(如 PostgreSQL 的 @> 操作符或 ILIKE,mysql 的 FIND_IN_SET,sqlite 的 LIKE),或更通用、跨库兼容的方式:使用 LIKE 配合 JSON 数组格式边界包裹

✅ 推荐方案:使用 LIKE 安全匹配(兼容主流数据库)

假设你的 category 字段在 postgresql/MySQL 中被序列化为 [“test1″,”test2″,”test3”](JSON 格式),可借助 LIKE 进行精确子串匹配,并添加引号与逗号/括号边界,避免误匹配(如 “test” 匹配 “test2″):

public async getBooksByCategory(   category: string,   page: number = 1, ): Promise<PageDto<BookEntity>> {   const queryBuilder = this.bookRepository.createQueryBuilder('book_entity');    // 安全匹配 JSON 数组中的精确 category 值(支持含引号、逗号的 category)   queryBuilder.where('book_entity.category LIKE :pattern', {     pattern: `%"${category}"%`,   });    queryBuilder.skip((page - 1) * 10).take(10);    const [entities, itemCount] = await queryBuilder.getManyAndCount();    return new PageDto<BookEntity>(entities, itemCount, page); }

? 原理说明:%”${category}”% 确保只匹配被双引号包裹的完整字符串项,规避 “test” 匹配 “test2” 或 “contest” 等歧义场景。

⚠️ 注意事项与最佳实践

  • 不要使用 IN (:…category):该语法适用于普通列或关系列,对 simple-array 字段无效,因底层存储非关系表,而是单字段字符串。
  • 避免 ILIKE ‘%test2%’(无引号):存在严重误匹配风险(如 test22、mytest2 均会被捕获)。
  • 生产环境建议迁移至 jsonb + 关系设计:长期来看,simple-array 不利于查询性能与扩展性。推荐重构为 @ManyToMany() 关联 CategoryEntity,从而获得原生索引、高效 JOIN 与类型安全。
  • PostgreSQL 用户可选优化:若使用 jsonb 类型(需修改实体):
    @Column({ type: 'jsonb', default: [] }) category: string[];

    则可用原生操作符:

    queryBuilder.where('book_entity.category @> :category', {    category: [`"${category}"`] // 注意:仍需转义为 JSON 字符串 });

✅ 完整服务方法示例(含错误处理与类型提示)

import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, SelectQueryBuilder } from 'typeorm'; import { BookEntity } from './book.entity'; import { PageDto } from '../common/dtos/page.dto';  @Injectable() export class BookService {   constructor(     @InjectRepository(BookEntity)     private readonly bookRepository: Repository<BookEntity>,   ) {}    async getBooksByCategory(     category: string,     page: number = 1,   ): Promise<PageDto<BookEntity>> {     if (!category?.trim()) {       throw new NotFoundException('Category cannot be empty');     }      const queryBuilder = this.bookRepository       .createQueryBuilder('book_entity')       .where('book_entity.category LIKE :pattern', {         pattern: `%"${category.trim()}"%`,       });      queryBuilder.skip((page - 1) * 10).take(10);      try {       const [entities, itemCount] = await queryBuilder.getManyAndCount();       return new PageDto<BookEntity>(entities, itemCount, page);     } catch (error) {       console.error('Failed to fetch books by category:', error);       throw error;     }   } }

通过以上实现,你即可在 NestJS 应用中安全、高效地按分类检索书籍,并无缝集成到现有分页体系中。记住:数据建模决定查询能力——当业务增长后,请优先考虑规范化关联设计,而非依赖 simple-array 的便利性。

text=ZqhQzanResources