惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
U
Unit 42
人人都是产品经理
人人都是产品经理
罗磊的独立博客
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
aimingoo的专栏
aimingoo的专栏
T
Tailwind CSS Blog
GbyAI
GbyAI
Blog — PlanetScale
Blog — PlanetScale
I
InfoQ
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
B
Blog RSS Feed
WordPress大学
WordPress大学
腾讯CDC
H
Help Net Security
博客园 - Franky
博客园 - 【当耐特】
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
B
Blog
Vercel News
Vercel News
博客园 - 司徒正美

mafeifan 的编程技术分享

mafengwo-mp3-downloader | mafeifan 的编程技术分享 示例页面 | mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 查看 default namespace 下的 default service account名称 mafeifan 的编程技术分享 检查日志 | mafeifan 的编程技术分享 bridge fdb show dev flannel.1 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享
mafeifan 的编程技术分享
2026-01-16 · via mafeifan 的编程技术分享

MySQL5.7.8 起支持定义JSON类型

这里已经建了一张表,叫 my_json,注意 meta 是 json 类型

image.png

建立相关的模型

<?php
namespace Modules\Models;

use Illuminate\Database\Eloquent\Model;

class MyJson extends Model
{

    public $table = 'my_json';


    public $fillable = [
         'meta'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var  array
     */
    protected $casts = [
        'id'             => 'number',
        'meta'           => 'array',
    ];
}

操作

// 新增
$model = new MyJson();
$model->meta =['name' => 'jack', 'age' => 18];
$model->save();

// 更新
$result = MyJson::query()
  ->where('id', 1)
  ->update(['meta->name' => 'lily', 'meta->age' => 28]);


//  可以插入复杂些的内容
$model = new MyJson();
$model->meta =[
   'deviceInfo' => [
          [
            'name' => '消防栓',
            'fields' => [
                ['id' => 1, 'type' => '1', 'label' => '消火栓箱体外观无破损现象'],
                ['id' => 2, 'type' => '2', 'label' => '消火栓箱箱门正面有标志牌,标注“消火栓”字样'],
                ['id' => 3, 'type' => '1', 'label' => '消火栓箱门开启角度可大于160度']
            ]
          ],
          [
            'name' => '灭火器',
            'fields' => [
                ['id' => 1, 'type' => '1', 'label' => '灭火器外观无破损现象'],
                ['id' => 2, 'type' => '2', 'label' => '灭火器正面有标志牌'],
            ]
          ]
        ]
      ];
$model->save();

// 当然更新时候会稍微麻烦些
$model = MyJson::query()->find(4);
$tmp = $model->meta;
$tmp['deviceInfo'][0]['name'] = 'll';
$model->meta = $tmp;
$model->save();
$result = MyJson::query()->find(4)->meta;

存到数据库里会自动转为JSON

image.png

总结:使用 Laravel 操作 MySQL 的 json类型还是很方便的,主要是建立表时要考虑好

参考 ​

https://www.cnblogs.com/wshenjin/p/10276678.htmlhttps://learnku.com/laravel/t/13185/in-depth-understanding-of-json-data-type-of-mysql-nosql-in-relational-database