SQL Server Issue querying a json value in laravel project

u4dcyp6a  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(136)

I'm trying to fetch a record from MSSQL table based on field value which contains json data. Following is the sample column value for 'updated_value' column:

[[{"phone_number":"5555555555","phone_type":"H","inactive_date":null,"restrictions":["SU","F"],"start_time":null,"end_time":null}]]

My query is:

$existing = ContactChangeLogs::latest()
        ->where('updated_value->phone_number', '5555555555')
        ->first();

But dd($existing) gives null result.

tcbh2hod

tcbh2hod1#

A possible approach is to use whereRaw() method to build a raw WHERE clause for your query. The actual statement depends on the JSON structure and in your case you need two OPENJSON() calls to parse the nested JSON content:

->whereRaw(
   "EXISTS (
      SELECT 1 
      FROM OPENJSON(updated_value) j1 
      CROSS APPLY OPENJSON(j1.[value]) j2 
      WHERE JSON_VALUE(j2.[value], '$.phone_number') = ?
    )",
    ['5555555555']
)

As an additional note, if the JSON content has this fixed structure (two nested arrays, the first one containing a single JSON array and the second one with a single JSON object as item), you may simplify the statement:

->whereRaw(
   "JSON_VALUE(updated_value, '$[0][0].phone_number') = ?",
    ['5555555555']
)
f4t66c6m

f4t66c6m2#

You can use the JSON_VALUE function to extract the 'phone_number' value from the JSON data

$existing = DB::select(
    "SELECT TOP 1 * 
       FROM contact_change_logs 
      WHERE JSON_VALUE(updated_value, '$[0].phone_number') = '5555555555'"
);
ao218c7q

ao218c7q3#

You can use whereJsonContains() instead of where() .

$existing = ContactChangeLogs::latest()
        ->whereJsonContains('updated_value->phone_number', '5555555555')
        ->first();

相关问题