[英]How to query row containing the given element inside a json column Laravel Postgres
Hello all I have a postgresql table that has a json column called agents. 大家好,我有一个postgresql表,其中有一个称为agent的json列。 See below 见下文
SELECT agents FROM cnms_rosters;
result 结果
agents
------------------
[1,13,3,16,15]
[12,13,14,15,15]
[11,73,55,16,44]
(3 rows)
This column contains the id of an agent. 此列包含代理的ID。 What I want to do is to query the row or rows that has the specific agent id. 我要查询的是具有特定代理ID的行。
How can I achieve that? 我该如何实现?
I am currently using Laravel Framework is there any eloquent approach in querying the data? 我目前正在使用Laravel Framework查询数据是否有雄辩的方法? if not how to query it using DB::raw or other query builder. 如果不是,如何使用DB :: raw或其他查询生成器查询它。
You can use regex searching from the model: 您可以从模型中使用正则表达式搜索:
CnmsRoster::where('agents', '~', "/[^0-9]{$agent_id}[^0-9]/")
The [^0-9]
is intended to match either a square bracket or a comma. [^0-9]
用于匹配方括号或逗号。 This lets you look inside the string for the numeric agent id you want sandwiched between control characters. 这使您可以在字符串内查找要夹在控制字符之间的数字代理ID。
sql query would be using @>
operator, eg: sql查询将使用@>
运算符,例如:
t=# with cnms_rosters(agents) as (values('[1,13,3,16,15]'::jsonb),('[12,13,14,15,15]'),('[11,73,55,16,44]'))
select agents FROM cnms_rosters where agents @> '[13]'::jsonb;
agents
----------------------
[1, 13, 3, 16, 15]
[12, 13, 14, 15, 15]
(2 rows)
or 要么
t=# with cnms_rosters(agents) as (values('[1,13,3,16,15]'::jsonb),('[12,13,14,15,15]'),('[11,73,55,16,44]'))
select agents FROM cnms_rosters where agents @> '[16]'::jsonb;
agents
----------------------
[1, 13, 3, 16, 15]
[11, 73, 55, 16, 44]
(2 rows)
and same for array: 与数组相同:
t=# with cnms_rosters(agents) as (values(array[1,13,3,16,15]),(array[12,13,14,15,15]),(array[11,73,55,16,44]))
select agents FROM cnms_rosters where agents @> array[13];
agents
------------------
{1,13,3,16,15}
{12,13,14,15,15}
(2 rows)
or 要么
t=# with cnms_rosters(agents) as (values(array[1,13,3,16,15]),(array[12,13,14,15,15]),(array[11,73,55,16,44]))
select agents FROM cnms_rosters where agents @> array[16];
agents
------------------
{1,13,3,16,15}
{11,73,55,16,44}
(2 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.