TypeORM PostgreSQL 选择 JSON 字段等于某个值的位置

问题描述 投票:0回答:9

目标:编写一个选择查询,返回状态等于“florida”的所有行。

实体栏:

  @Column({ type: 'json'})
  public address: Address;

示例列值:

{"city": "miami", "state": "florida"}

示例查询(不起作用):

getManager().getRepository(User)
    .createQueryBuilder('user')
    .select()
    .where('user.address.state =:state', {state: "florida"})

typeorm 目前支持此功能吗?如果是这样,我需要如何修改我的 where 子句才能返回正确的行?

postgresql typeorm
9个回答
19
投票

另一种可能的解决方案(原始SQL不能用此注入):

.where('user.address ::jsonb @> :address', {
    address: {
        state: query.location
    }
})

这样,TypeORM 将生成一个以

结尾的 SQL 查询
WHERE user.address ::jsonb @> $1

并且将给出查询,例如

{ state: 'florida' }

作为查询参数来替换查询中的正确值($1)。

来源:主要是原来的问题+答案(谢谢!)+自己的测试+https://www.postgresql.org/docs/9.4/functions-json.html


16
投票

成功了。

正确语法:

.where(`user.address ::jsonb @> \'{"state":"${query.location}"}\'`)

9
投票

它对我有用:

.getRepository(User)
.createQueryBuilder('user')
.where(`user.address->>'state' = :state`, {state: "florida"})

2
投票
    return getRepository(User)
    .createQueryBuilder()
    .where('address @> :address', {
      address: { state: "florida" },
    })
    .getMany();

1
投票

试试这个:

   const users = await getManager()
  .getRepository(UserEntity)
  .createQueryBuilder(`user`)
  .where("address->>'state' = :state")
  .setParameters({ state })
  .getMany();

1
投票

.where("user.address->>'state' = :state", {state: "佛罗里达"}).getMany();


0
投票
.where(`user.address -> '$.state' = :state`, {state: "florida"})

0
投票

更现代的方法是使用 JsonContains

import { JsonContains } from 'typeorm'

repo.find({
    where: { address: JsonContains({ state: 'florida' }) },
});

-6
投票

这对我有用。我只是使用 TypeORM 之类的函数。

.find({
   where: {
      address: Like(`%${add what to search for here}%`),
   },
});
© www.soinside.com 2019 - 2024. All rights reserved.