Laravel-sql搜索json类型列


Laravel sql search json type column

mysql有一个表"subscribe"表,如下所示:

column   type
id        int
condition  json
type_id    id

示例如下:

"id": "1",
"condition": "{'"id'":'"2'",'"class'":'"master'",'"zone'":'"west'",'"price'":'"511'"}",
"type_id": "1"

并且我想选择在列条件中匹配的列,如"zone"="west"laravel 5.2支持订单

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

错误

 Column not found: 1054 Unknown column 'condition->class' in 'where clause'(
SQL: select * from `subscribe` where `condition->class` = master)

我需要得到符合conditon->class=master条件的项。我需要在模型中选择符合需要的数据。我不知道怎么了。任何帮助都将不胜感激。

我相信正确的语法是:

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

请参阅本段下面的示例,位于https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

  • 列->路径

在MySQL 5.7.9及更高版本中,->当与两个参数一起使用时,运算符充当JSON_EXTRACT()函数的别名,左边是列标识符,右边是根据JSON文档(列值)计算的JSON路径。无论列标识符出现在SQL语句中的哪个位置,都可以使用此类表达式来代替它们。

问题是查询中的where子句被视为condition->class中的列名,而不是laravel代码。您希望从json中提取值。但查询不理解这一点。

您需要做的是将整个表以json格式传递给视图,然后在视图中提取。

我建议这样做:在这里,$subscribe在json中拥有整个表。您可以通过以下方式访问:

$subscribe = DB::table('subscribe')->all();
return response()->json(array('subscribe' => $subscribe));

然后在视图中做:

@if($subscribe->condition->class == 'master')
id      : {{ $subscribe->id }}
type id : {{ $subscribe->type_id }}
@endif

更新的代码

//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
}

像这样的东西做的技巧