我有一個名為的模型orders,它有一個infojson 列。在那個 json 中,我有一個名為id. 現在我想檢索所有具有6例如 id 的訂單。所以這就是我的做法如下:
$order = \DB::table('orders')
->where('info.id',$value)
// ->where('info->id',$value)
// ->whereRaw('JSON_EXTRACT(`info` , "$.id") = '.$value)
->first();
第三個whereRaw正在作業,但我認為它有一個錯誤,因為在我的驗證中,第三個或第四個回傳了這個非常奇怪的錯誤:
Column not found: 1054 Unknown column '6112 ' in 'where clause' (SQL: select * from `orders` where JSON_EXTRACT(`info` , "$.id") = 6112 limit 1)
它有些錯誤地將列值作為列名,這很奇怪,因為當我dd從查詢中獲取值時它在第一個值上作業,但它像第四個一樣中斷。現在我想知道是否有任何更簡單的解決方案可以在 json 欄位上使用 where 或者 whereRaw 有什么問題
uj5u.com熱心網友回復:
Laravel 支持在提供 JSON 列型別支持的資料庫上查詢 JSON 列型別。
目前,這包括 MySQL 5.7 、PostgreSQL、SQL Server 2016 和 SQLite 3.9.0(帶有JSON1 擴展名)。
要查詢 JSON 列,請使用->運算子:
$order = DB::table('orders')
->where('info->id', $value)
->first();
來自檔案的附加資訊:JSON Where Clauses
您可以使用whereJsonContains查詢 JSON 陣列。SQLite 資料庫不支持此功能:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();
如果您的應用程式使用 MySQL 或 PostgreSQL 資料庫,您可以將一組值傳遞給該whereJsonContains方法:
$users = DB::table('users')
->whereJsonContains('options->languages', ['en', 'de'])
->get();
您可以使用whereJsonLength方法按長度查詢 JSON 陣列:
$users = DB::table('users')
->whereJsonLength('options->languages', 0)
->get();
$users = DB::table('users')
->whereJsonLength('options->languages', '>', 1)
->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426313.html
標籤:php mysql 拉拉维尔 mysql-json
