简体   繁体   中英

Search in Json column with Laravel

In my emails table, I have a column named To with column-type 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". 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. Is there a better way to search using 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.

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

In case to store array in json format. And just have an array list of IDs, I did this.

items is the column name and $item_id is the term I search for

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

Checkout the Laravel API docs for the whereJsonContains method https://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_whereJsonContains

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

You can use where clause with like condition

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

Alternatively, if you have Model mapped to emails table names as Email using Eloquent

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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