PostgreSQL+TypeORM如何查询text[]类型字段包含指定值的行
PostgreSQL + TypeORM 查询text[]字段包含指定值的实现方法
方法一:使用QueryBuilder(灵活可控)
通过PostgreSQL的@>数组包含操作符,结合TypeORM QueryBuilder实现精确匹配:
import { getRepository } from "typeorm"; import { YourEntity } from "./entities/YourEntity"; // 替换为你的实体类 async function findEntitiesByAuthor(authorName: string) { const repo = getRepository(YourEntity); const result = await repo .createQueryBuilder("entity") .where("entity.authors @> ARRAY[:authorName]::text[]", { authorName }) .getMany(); return result; }
@>操作符用于判断左侧数组是否包含右侧数组的所有元素,这里传入单元素数组实现单个作者的精确匹配。
方法二:使用Repository的find方法(简洁直观)
TypeORM针对PostgreSQL数组类型提供了内置的contains查询选项,无需手动编写SQL片段:
async function findEntitiesByAuthor(authorName: string) { const repo = getRepository(YourEntity); const result = await repo.find({ where: { authors: { contains: [authorName] } } }); return result; }
底层同样基于@>操作符实现,代码更简洁易读。
方法三:使用ANY操作符(逻辑直白)
通过ANY操作符直接检查目标值是否存在于数组中:
async function findEntitiesByAuthor(authorName: string) { const repo = getRepository(YourEntity); const result = await repo .createQueryBuilder("entity") .where(":authorName = ANY(entity.authors)", { authorName }) .getMany(); return result; }
这种写法逻辑更直接,适合简单的存在性判断场景。
实体类字段定义参考
确保你的实体类中authors字段正确声明为PostgreSQL的text数组类型:
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"; @Entity() export class YourEntity { @PrimaryGeneratedColumn() id: number; @Column("text", { array: true }) authors: string[]; }
内容的提问来源于stack exchange,提问作者Văn Hào Trương
相关产品推荐
相关产品推荐

