Laravel Eloquent支持JSON字段查询与更新,使用->操作符访问键值,如profile->age;支持嵌套查询如profile->address->province;可用whereJsonContains查询数组内容;结合$casts属性自动转换JSON字段为数组,提升开发效率。

Laravel Eloquent 对 JSON 字段的查询提供了良好的支持,尤其是在 MySQL 5.7+ 或 PostgreSQL 等支持 JSON 类型的数据库中。你可以直接在 Eloquent 模型中查询 JSON 字段的特定键值,而无需将整个字段读取到 PHP 中再处理。
Laravel 使用 -> 操作符来访问数据库中的 JSON 字段。在 Eloquent 查询中,你可以通过 字段名->键名 的方式查询 JSON 中的具体值。
例如,假设 users 表中有一个 profile JSON 字段,存储了用户信息:
{ "age": 25, "city": "Beijing" }你可以这样查询 age 为 25 的用户:
User::where('profile->age', 25)->get();如果 JSON 值是字符串,也可以使用 like 进行模糊匹配:
User::where('profile->city', 'like', '%Bei%')->get();对于多层嵌套的 JSON 数据,Laravel 同样支持路径查询。比如 profile 包含 address 子对象:
{ "address": { "province": "Beijing", "district": "Haidian" } }可以使用如下语法查询:
User::where('profile->address->province', 'Beijing')->get();除了查询,Eloquent 也支持直接更新 JSON 字段中的某个键:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
User::where('id', 1)->update([
'profile->age' => 26,
'profile->city' => 'Shanghai'
]);你也可以在模型实例上操作:
$user = User::find(1); $user->profile['age'] = 26; $user->save();
当 JSON 字段中包含数组时,可使用 whereJsonContains 方法。例如 tags 字段存储了兴趣标签:
"tags": ["php", "laravel"]查找包含 "laravel" 标签的用户:
User::whereJsonContains('tags', 'laravel')->get();注意:MySQL 要求字段为 JSON 类型,否则可能无法正确匹配。
推荐在 Eloquent 模型中使用 $casts 属性将字段自动转为数组或对象:
protected $casts = [
'profile' => 'array',
'tags' => 'array'
];设置后,访问 $user->profile 时会自动解析为数组,保存时也会自动编码为 JSON 字符串。
基本上就这些。合理使用 JSON 查询能简化结构设计,但要注意避免过度嵌套,影响查询性能和可维护性。
以上就是laravel Eloquent如何处理JSON字段的查询_Laravel Eloquent JSON字段查询处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号