目标:编写一个选择查询,返回状态等于“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 子句才能返回正确的行?
另一种可能的解决方案(原始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
成功了。
正确语法:
.where(`user.address ::jsonb @> \'{"state":"${query.location}"}\'`)
它对我有用:
.getRepository(User)
.createQueryBuilder('user')
.where(`user.address->>'state' = :state`, {state: "florida"})
return getRepository(User)
.createQueryBuilder()
.where('address @> :address', {
address: { state: "florida" },
})
.getMany();
试试这个:
const users = await getManager()
.getRepository(UserEntity)
.createQueryBuilder(`user`)
.where("address->>'state' = :state")
.setParameters({ state })
.getMany();
.where("user.address->>'state' = :state", {state: "佛罗里达"}).getMany();
.where(`user.address -> '$.state' = :state`, {state: "florida"})
更现代的方法是使用 JsonContains。
import { JsonContains } from 'typeorm'
repo.find({
where: { address: JsonContains({ state: 'florida' }) },
});
这对我有用。我只是使用 TypeORM 之类的函数。
.find({
where: {
address: Like(`%${add what to search for here}%`),
},
});