JSON数据包括JSON类型以及JSON格式(并不是JSON类型字段)的数据

User模型类

use thinkModel;
class User extends Model{// 设置json类型字段
protected $json = ['info'];
}

进行JSON数据操作

写入JSON数据

使用数组方式写入JSON数据

$user = new User;
$user->name = 'thinkphp';
$user->info = ['email'=> 'thinkp@qq.com','nickname '=> '年',];
$user->save();

使用对象方式写入JSON数据

$user = new User;
$user->name = 'thinkphp';
$info = new StdClass();
$info->email = 'think@qq.com';
$info->nickname = '年';
$user->info = $info;
$user->save();

查询JSON数据

$user = User::get(1);
echo $user->name;
echo $user->info->email; // think@qq.com
echo $user->info->nickname; // 年

查询条件为JSON数据

$user = User::where('info->nickname','年')->find();
echo $user->name; // think
echo $user->info->email; // think@qq.com
echo $user->info->nickname; // 年

查询的JSON属性是整型类型 需要进行手动参数绑定。

$user = User::where('info->user_id',':user_id')->bind('user_id', 10 ,PDO::PARAM_INT)->find();
echo $user->name; // think
echo $user->info->email; // think@qq.com
echo $user->info->nickname; // 年

V5.1.11+在模型类里面定义JSON字段的属性类型 就会自动进行相应类型的参数绑定查询

use thinkModel;
class User extends Model{// 设置json类型字段
protected $json = ['info'];    // 设置JSON字段的类型
protected $jsonType = ['user_id'=>'int' ];
}

没有定义类型的属性默认为字符串类型 因此字符串类型的属性可以无需定义。

更新JSON数据

$user = User::get(1);
$user->name = 'kancloud';
$user->info->email = 'kancloud@qq.com';
$user->info->nickname = 'kancloud';
$user->save();