Laravel sql search json type column

放肆的年华 提交于 2019-12-06 17:04:32

I believe the correct syntax is:

 $subscribe = DB::table('subscribe')->where('condition->"$.class"', 'master')->get();

See the example below this paragraph, on https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

  • column->path

In MySQL 5.7.9 and later, the -> operator serves as an alias for the JSON_EXTRACT() function when used with two arguments, a column identifier on the left and a JSON path on the right that is evaluated against the JSON document (the column value). You can use such expressions in place of column identifiers wherever they occur in SQL statements.

The thing is the where clause in query is considering as a column name in condition->class and not as a laravel code. you want to extract the value from json. but the query doesn't understand that.

What you need to do is pass entire table as it is in json format to the view and then extract in the view.

I suggest do something like this : Here, $subscribe has entire table in json . which you can access it by :

$subscribe = DB::table('subscribe')->all();

return response()->json(array('subscribe' => $subscribe));

Then in the view do:

@if($subscribe->condition->class == 'master')

id      : {{ $subscribe->id }}
type id : {{ $subscribe->type_id }}

@endif

Updated Code

//get condition in json
$subscribe = DB::table('subscribe')->select('condition')->get();

then, 

// convert json to array
$subscribe_array = json_decode($subscribe, true);
//  create a new collection instance from the array
$collection_array = collect($subscribe_array);


if($collection_array['class'] == 'master')
{

//do something

}

Something like this do the trick

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