laravel通过$casts自动处理jsON字段的序列化与反序列化,支持Array/Object/Collection类型;需用数据库原生json函数(如JSON_SET)实现局部更新;提供whereJsonContains、whereJsonLength等查询方法适配多数据库;可配合访问器/修改器定制逻辑。

在 Laravel 中操作 JSON 类型字段(如 mysql 5.7+ 的 JSON 类型、postgresql 的 jsonb 或 sqlite 的文本模拟),Eloquent 提供了原生支持,无需手动序列化/反序列化。关键在于正确设置模型属性和使用访问器、修改器或直接查询语法。
1. 模型中声明 JSON 字段为数组/对象类型
Laravel 会自动将 JSON 字段转为 php 数组(或 StdClass 对象),前提是该字段被标记为 $casts 中的 'array'、'object' 或 'collection':
class User extends Model { protected $casts = [ 'preferences' => 'array', // 存储为 JSON,读取为关联数组 'settings' => 'object', // 读取为 StdClass 实例 'tags' => 'collection', // 自动转为 IlluminateSupportCollection ]; }
这样写入时传数组,Laravel 自动 json_encode;读取时自动 json_decode,无需手动处理。
2. 写入和更新 JSON 字段(整体或局部)
整体更新直接赋值即可:
- 整字段替换:
$user->preferences = ['theme' => 'dark', 'notifications' => true]; $user->save(); - 局部更新(MySQL 5.7+):用
DB::raw()或 Eloquent 的whereJsonContains/whereJsonLength等方法,但「局部更新」需用原生 JSON 函数:
// 更新 preferences.theme 而不覆盖整个字段(MySQL) DB::table('users') ->where('id', 1) ->update([ 'preferences' => DB::raw("JSON_SET(preferences, '$.theme', 'light')") ]); // 或用模型:$user->update(['preferences' => DB::raw("JSON_SET(...)")]);
注意:Eloquent 默认不支持「只改 JSON 内某个键」的语法糖,必须借助数据库原生 JSON 函数。
3. 查询 JSON 字段(条件检索)
Laravel 支持多种 JSON 查询语法,适配不同数据库:
- 包含某个值(MySQL/PG):
User::whereJsonContains('preferences', ['notifications' => true])->get(); - 指定路径匹配(MySQL):
User::where('preferences->theme', 'dark')->get();(等价于JSON_EXTRACT(preferences, '$.theme')) - 数组长度判断(MySQL):
User::whereJsonLength('tags', '>', 2)->get(); - PostgreSQL 特有(推荐用
->>获取文本):User::where('settings->language', 'en')->get();
这些方法底层调用对应数据库的 JSON 函数,Laravel 自动适配方言。
4. 使用访问器/修改器做自定义处理
若需对 JSON 字段做转换逻辑(比如统一添加默认键、过滤敏感字段),可配合 getFooAttribute 和 setFooAttribute:
class User extends Model { protected $casts = ['metadata' => 'array']; // 读取时补充默认值 public function getMetadataAttribute($value) { return array_merge(['version' => '1.0'], $value); } // 写入时过滤掉非法键 public function setMetadataAttribute($value) { $allowed = ['theme', 'locale', 'timezone']; $this->attributes['metadata'] = array_intersect_key($value, array_flip($allowed)); } }
注意:修改器中不要调用 $this->metadata = ...,否则会触发无限递归;应直接操作 $this->attributes。
基本上就这些。核心是善用 $casts 做自动转换,结合数据库原生 JSON 函数做高级查询和局部更新,再按需用访问器/修改器增强逻辑。不复杂但容易忽略细节,比如忘记声明 cast 导致存成字符串,或误以为 -> 语法能直接更新子字段。
以上就是Laravel如何操作JSON类型的数据库字段?(Eloquent示例)的详细内容,更多请关注php中文网其它相关文章!