use*_*572 4 postgresql typeorm
目标: 编写一个选择查询,返回状态等于“佛罗里达”的所有行。
实体栏:
@Column({ type: 'json'})
public address: Address;
Run Code Online (Sandbox Code Playgroud)
样本列值:
{"city": "miami", "state": "florida"}
Run Code Online (Sandbox Code Playgroud)
查询示例(无效):
getManager().getRepository(User)
.createQueryBuilder('user')
.select()
.where('user.address.state =:state', {state: "florida"})
Run Code Online (Sandbox Code Playgroud)
typeorm当前支持此功能吗?如果是这样,我该如何修改我的where子句以返回正确的行?
小智 9
这个对我有用:
.getRepository(User)
.createQueryBuilder('user')
.where(`user.address->>'state' = :state`, {state: "florida"})
Run Code Online (Sandbox Code Playgroud)
得到它的工作。
正确的语法:
.where(`user.address ::jsonb @> \'{"state":"${query.location}"}\'`)
Run Code Online (Sandbox Code Playgroud)
另一种可能的解决方案(原始 SQL 不能注入此):
.where('user.address ::jsonb @> :address', {
address: {
state: query.location
}
})
Run Code Online (Sandbox Code Playgroud)
这样,TypeORM 将生成一个以
WHERE user.address ::jsonb @> $1
Run Code Online (Sandbox Code Playgroud)
并且将给出查询,例如
{ state: 'florida' }
Run Code Online (Sandbox Code Playgroud)
作为查询参数来替换查询中的正确值 ($1)。
来源:主要是原题+答案(谢谢!)+自己测试+ https://www.postgresql.org/docs/9.4/functions-json.html
| 归档时间: |
|
| 查看次数: |
2446 次 |
| 最近记录: |