JSON(JavaScript Object Notation, JS 对象简谱)是一种轻量级的数据交换格式
它基于 ECMAScript(European Computer Manufacturers Association,欧洲计算机协会制定的 JS 规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据
简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言
易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率

MySQL 5.7.8 开始支持 JSON 类型,Laravel 从 5.3 开始加入了 JSON 类型支持
下面用一个示例表来学习本类型的 CURD
表结构:
1 | create table product |
Laravel 中定义此 Model:
1 | class Product extends Model |
需要在 $casts 属性中声明 JSON 格式字段
新增
原生 SQL
1 | INSERT INTO product VALUES (1, '{"color": "黑色", "size": "XXL"}'); |
Model 新增
1 | $product = new Product(); |
修改
原生 SQL
1 | UPDATE product SET attribute = JSON_SET(attribute, '$.color', '黑') WHERE id = 1 |
JSON_SET()替换已经存在的值,增加不存在的值JSON_INSERT()新增不存在的值JSON_REPLACE()替换/修改已经存在的值
Model 修改
1 | Product::find(2)->update([ |
查询
原生 SQL
1 | SELECT * FROM product WHERE `attribute`->'$.color'= '黑色' |
Model 查询
1 | Product::where('attribute->color', '黑色')->get(); |
删除
原生 SQL
1 | UPDATE product SET attribute = JSON_REMOVE(`attribute`, '$."color"') WHERE id = 1; |
JSON_REMOVE() – Remove Data from a JSON Document in MySQL
Model 删除
1 | Product::find(1)->update([ |