laravel json字段查询需注意路径写法、类型匹配与方法选择:一、箭头语法用于精确路径匹配;二、wherejsoncontains用于数组或对象片段匹配;三、wherejsonlength按数组长度筛选;四、需处理null或路径不存在情况;五、select中可用箭头语法提取并别名输出json值。

如果您在 Laravel 应用中需要从数据库 JSON 字段中提取或匹配特定值,但查询结果为空或返回意外数据,则可能是由于路径写法错误、类型不匹配或方法选用不当。以下是针对 JSON 字段的多种标准查询方式:
一、使用箭头语法进行精确路径匹配
该方法适用于已知 JSON 结构且需对某个键做等值、范围或模糊比较的场景,Laravel 会自动将 info->id 编译为对应数据库的原生 JSON 提取函数,并通过参数绑定确保安全性。
1、在 Eloquent 模型中查询 profile->age 等于 25 的用户:
User::where('profile->age', 25)->get();
2、查询嵌套字段 profile->address->district 为 "Haidian" 的记录:
User::where('profile->address->district', 'Haidian')->get();
3、执行范围比较,如 profile->age 大于 18:
User::where('profile->age', '>', 18)->get();
4、结合 like 进行模糊匹配 city 字段:
User::where('profile->city', 'like', '%jing%')->get();
二、使用 whereJsonContains 匹配 JSON 数组或对象片段
该方法专用于判断 JSON 字段是否包含指定值或键值对,底层调用数据库原生函数(如 MySQL 的 JSON_CONTAINS 或 PostgreSQL 的 @>),确保语义正确和结构化匹配。
1、查找 info->tags 数组中包含字符串 "urgent" 的订单:
DB::table('orders')->whereJsonContains('info->tags', 'urgent')->get();
2、同时匹配多个标签(AND 逻辑):
DB::table('orders')->whereJsonContains('info->tags', ['urgent', 'paid'])->get();
3、匹配 JSON 对象中的键值对,例如 status 为 active:
DB::table('orders')->whereJsonContains('info', ['status' => 'active'])->get();
4、在控制器中接收请求参数并查询 meta->form_id 包含指定 ID 的记录:
$formId = request()->id;
YourModel::whereJsonContains('meta->form_id', $formId)->get();
三、使用 whereJsonLength 按 JSON 数组长度筛选
该方法适用于需根据 JSON 数组元素数量进行过滤的场景,支持等于、大于、小于等比较操作,可精准控制数组规模。
1、查找 info->items 数组长度恰好为 3 的订单:
DB::table('orders')->whereJsonLength('info->items', 3)->get();
2、查找 tags 数组长度大于 1 的记录:
DB::table('orders')->whereJsonLength('info->tags', '>', 1)->get();
3、查找 items 数组非空(长度大于 0)的订单:
DB::table('orders')->whereJsonLength('info->items', '>', 0)->get();
四、处理 NULL 或路径不存在的边界情况
当 JSON 字段本身为 NULL,或指定路径(如 info->id)在数据中根本不存在时,直接使用 where('info->id', $value) 将无法匹配任何记录,必须显式覆盖空值逻辑。
1、允许 info 字段为 NULL 或 info->id 不存在,但仍匹配 id 值为 6 的记录:
DB::table('orders')->whereNull('info')->orWhere('info->id', 6)->get();
2、更安全的写法:先确保 info 非空,再进行路径匹配:
DB::table('orders')->whereNotNull('info')->where('info->id', 6)->get();
3、若需兼容 NULL 路径值(即 info 存在但 info->id 为 null),应改用 whereRaw 配合 IS NULL 判断(仅限必要场景):
DB::table('orders')->whereRaw('JSON_EXTRACT(info, "$.id") IS NULL OR info->id = ?', [6])->get();
五、在 select 中提取 JSON 字段值并别名输出
该方法用于在查询结果中直接展开 JSON 内容,避免应用层二次解析,提升响应效率,且支持 as 别名便于前端消费。
1、从 users 表中选取 id 和 profile->city 并命名为 city:
User::select('id', 'profile->city as city')->get();
2、提取嵌套字段 profile->address->postal_code 并别名为 code:
User::select('id', 'profile->address->postal_code as code')->get();
3、同时提取多个 JSON 子字段:
User::select('id', 'profile->age as age', 'profile->city as city')->get();
4、在查询构造器中使用相同语法:
DB::table('users')->select('id', 'profile->email as email')->get();











