typeorm postgres select where json field equals some value

半世苍凉 提交于 2021-01-27 05:40:16

问题


Goal: write a select query that returns all rows where state equals "florida".

Entity column:

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

Sample column value:

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

Example query (doesn't work):

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

Is this functionality currently supported in typeorm? If so, how would I need to modify my where clause to return the correct rows?


回答1:


Got it working.

Correct syntax:

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



回答2:


Another possible solution (raw SQL can not be injected with this):

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

With this, TypeORM will produce an SQL query ending with

WHERE user.address ::jsonb @> $1

and the query will be given e.g.

{ state: 'florida' }

as a query parameter to replace the right value ($1) in the query.

Sources: Mainly the original question + answer (thank you!) + own testing + https://www.postgresql.org/docs/9.4/functions-json.html




回答3:


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



回答4:


This works for me. I just use TypeORM like function.

.find({
   where: {
      address: Like(`%${add what to search for here}%`),
   },
});


来源:https://stackoverflow.com/questions/52808304/typeorm-postgres-select-where-json-field-equals-some-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!