前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Laravel 操作mysql json类型

Laravel 操作mysql json类型

作者头像
mafeifan
发布2019-08-20 11:30:42
2K0
发布2019-08-20 11:30:42
举报
文章被收录于专栏:finleyMafinleyMa

MySQL5.7 起支持定义JSON类型

这里已经建了一张表,叫 my_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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.08.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档