首页 > 解决方案 > Postgres中的Typeorm查询数组类型

问题描述

const query = userConnection.getRepository(User).createQueryBuilder('user');

const result = await query.where("user.role @> ARRAY[:role]", { role: 'Super-Admin' })
               .getMany();

return result;

实体

@Entity()
export class User extends BaseEntity{
    @Column({type: 'text', array: true})
    role: UserRole[];
}

我收到错误'操作员不存在:文本@>文本[]'

我在这里做错了什么?

标签: postgresqlnestjstypeorm

解决方案


https://www.postgresql.org/docs/9.1/functions-comparisons.html

expression operator ANY (array expression)

右边是一个带括号的表达式,它必须产生一个数组值。使用给定的运算符计算左侧表达式并与数组的每个元素进行比较,该运算符必须产生布尔结果。如果获得任何真结果,则 ANY 的结果为“真”。如果没有找到真正的结果(包括数组有零元素的情况),则结果为“假”。

所以你可以使用ANY函数来查找用户具有多个包含管理员的角色

const result = await query.where(':role = ANY (user.role)', { role: 'Super-Admin' });

推荐阅读