簡體   English   中英

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"

並且我想選擇在列條件中匹配的列,例如laravel 5.2支持該列的“ zone” =“ west”

 $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

}

這樣的事情就可以了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM