Search multidimensional jsonb data in laravel postgres

跟風遠走 提交于 2020-01-13 06:48:27

问题


I have multiple jsonb data fields in my postgres database. Like my Contacts table has name, addresses, phones and emails as jsonb data fields. Most of the jsonb data fields are multidimensional. Like emails field have different json data for different email types. Following is the sample emails data i have in my database.

[
    {"tag": "Home", "value": "foo@bar.com"}, 
    {"tag": "Other", "value": "john@doe.net"}, 
    {"tag": "Work", "value": "john@foo.com"}, 
    {"tag": "Home", "value": "foo@gmail.com"}
]

I want to execute a search on emails field's value data. Like i want to fetch all the contacts with email john@doe.net in emails field.

I have tried to fetch the contacts with normal where query like

$contacts = Contact::where('emails->value', 'ilike', "%$query%")->get();

But it does not return anything and that is obvious because emails field is multidimensional. Although on a single dimensional json data this query works fine.

What is the proper way of searching such data fields in laravel eloquent ?. It will be better if it can be done without using whereRaw with jsonb_exists function.


回答1:


I got it working and posting the answer here if in case anyone needs help in future.

Basically we can do a simple where query with @> operator. And the value can be json encoded with the searched email. Following is the query to search for particular email without using whereRaw method.

$contacts = Contact::where("emails", '@>', '[' . json_encode(['value' => $query]) . ']')->get();

Hope it helps some one else in future :)



来源:https://stackoverflow.com/questions/47658567/search-multidimensional-jsonb-data-in-laravel-postgres

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