I've got this data in a JSONB field:
我在JSONB字段中获得了这些数据:
[
'first_name' => 'Philipp',
'last_name' => 'Kühn',
'size' => 170,
'hobbies' => [
'daily' => 'beer',
],
'skills' => [
'drink beer',
'drink more beer',
],
]
I'm pretty new to Laravel and Postgres so I wanted to do some basic queries.
我对Laravel和Postgres非常陌生,所以我想做一些基本的查询。
Here are some queries that works fine: (json is the name of the column)
以下是一些运行良好的查询:(json是列的名称)
$users = User::whereRaw("json ->> 'first_name' = 'Philipp'")->get();
$users = User::whereRaw("json ->> 'size' > '160'")->get();
$users = User::whereRaw("json #>> '{hobbies, daily}' = 'beer'")->get();
Now I want to check if drink beer
is in skills
and the following code doesn't work:
现在我想检查一下喝啤酒是否有技巧,下面的代码是否有效:
$users = User::whereRaw("json -> 'skills' ? 'drink beer'")->get();
Here I got a syntax error:
这里有一个语法错误:
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1"
LINE 1: select * from "users" where json ->> 'skills' $1 'drink beer...
^ (SQL: select * from "users" where json ->> 'skills' ? 'drink beer')
How can I search for drink beer
?
我怎么能搜索喝啤酒?
1 个解决方案
#1
3
As suggested by @tapoueh on twitter, maybe a work around would be to use the operator's underlying function: jsonb_exists(jsonb, text)
. So your query would be
正如@tapoueh在twitter上建议的那样,可能需要使用运营商的底层功能:jsonb_exists(jsonb, text)。所以你的查询是。
$users = User::whereRaw("jsonb_exists(json -> 'skills', 'drink beer')")->get();
Added by @docteur_klein : A link to a similar problem.
@docteur_klein添加了一个类似问题的链接。
#1
3
As suggested by @tapoueh on twitter, maybe a work around would be to use the operator's underlying function: jsonb_exists(jsonb, text)
. So your query would be
正如@tapoueh在twitter上建议的那样,可能需要使用运营商的底层功能:jsonb_exists(jsonb, text)。所以你的查询是。
$users = User::whereRaw("jsonb_exists(json -> 'skills', 'drink beer')")->get();
Added by @docteur_klein : A link to a similar problem.
@docteur_klein添加了一个类似问题的链接。