简体   繁体   English

使用 Laravel 在 Json 列中搜索

[英]Search in Json column with Laravel

In my emails table, I have a column named To with column-type Json .在我的电子邮件表中,我有一个名为To的列,列类型为Json This is how values are stored:这是存储值的方式:

[
    {
        "emailAddress": {
            "name": "Test", 
            "address": "test@example.com"
        }
    }, 
    {
        "emailAddress": {
            "name": "Test 2", 
            "address": "test2@example.com"
        }
    }
]

Now I want a collection of all emails sent to "test@example.com".现在我想要发送到“test@example.com”的所有电子邮件的集合。 I tried:我试过:

DB::table('emails')->whereJsonContains('to->emailAddress->address', 'test@example.com')->get();

(see https://laravel.com/docs/5.7/queries#json-where-clauses ) but I do not get a match. (请参阅https://laravel.com/docs/5.7/queries#json-where-clauses )但我没有找到匹配项。 Is there a better way to search using Laravel (Eloquent)?有没有更好的方法来使用 Laravel (Eloquent) 进行搜索?

In the debugbar, I can see that this query is "translated" as:在调试栏中,我可以看到此查询被“翻译”为:

select * from `emails` where json_contains(`to`->'$."emailAddress"."address"', '\"test@example.com\"'))

The arrow operator doesn't work in arrays.箭头运算符在数组中不起作用。 Use this instead:改用这个:

DB::table('emails')
   ->whereJsonContains('to', [['emailAddress' => ['address' => 'test@example.com']]])
   ->get()

I haven't used the json column but as the documentation refers, the below code should work fine.我没有使用 json 列,但正如文档所指,下面的代码应该可以正常工作。

DB::table('emails')
  ->where('to->emailAddresss->address','test@example.com')
  ->get();

In case to store array in json format.如果以 json 格式存储数组。 And just have an array list of IDs, I did this.只要有一个 ID 数组列表,我就是这样做的。

items is the column name and $item_id is the term I search for items 是列名, $item_id 是我搜索的词

// $item_id = 2
// items = '["2","7","14","1"]'
$menus = Menu::whereJsonContains('items', $item_id)->get();

Using Eloquent => Email::where('to->emailAddress->address','test@example.com')->get();使用 Eloquent => Email::where('to->emailAddress->address','test@example.com')->get();

You can use where clause with like condition您可以在类似条件下使用 where 子句

DB::table('emails')->where('To','like','%test@example.com%')->get();

Alternatively, if you have Model mapped to emails table names as Email using Eloquent或者,如果您使用 Eloquent 将模型映射到电子邮件表名称作为电子邮件

Email::where('To','like','%test@example.com%')->get(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM