Php 带有json类型字段的Laravel数据库添加\“;返回值时
我已经阅读了Laravel5文档,看到它支持数据库中的json类型字段,但我注意到了非常奇怪的行为 这是我的桌子:Php 带有json类型字段的Laravel数据库添加\“;返回值时,php,json,laravel,laravel-5,Php,Json,Laravel,Laravel 5,我已经阅读了Laravel5文档,看到它支持数据库中的json类型字段,但我注意到了非常奇怪的行为 这是我的桌子: Schema::create('subjects', function ($table) { $table->increments('id'); $table->string('name', 100); $table->integer('ects'); $table->json('studie
Schema::create('subjects', function ($table) {
$table->increments('id');
$table->string('name', 100);
$table->integer('ects');
$table->json('studies'); // this is my json type field
$table->date('created_at');
$table->date('updated_at');
});
然后,我使用以下内容为数据库添加种子:
Subject::create(['name' => 'Programming 1',
'ects' => '0',
'studies' => '{"program":"Computer Science","year":"1"}']);
服务器响应如下所示:
{
"id": 15,
"name": "Programming 1",
"brEcts": 0,
"studies": "{\"program\":\"Computer Science\",\"year\":\"1\"}",
"created_at": "2015-12-05 00:00:00",
"updated_at": "2015-12-05 00:00:00",
"pivot": {
"profesor_id": 20,
"subject_id": 15
}
}
注意响应字段研究中的\“和laravel为我生成的“pivot”字段结构正确,也是json类型的字段
当我查看phpMyAdmin时,研究字段的值看起来正常。(不带“\”)
我的服务器响应代码:
$subjects = Profesor::find($id)->subjets()->get();
return response()->json($subjects);
我是否正确地为数据库设置种子,或者问题是在服务器上返回值时
我知道我可以在客户端删除符号“\”来解决这个问题,但这是我最后的选择,因为它不够干净
编辑:
我通过在模型类中添加一个数组强制转换解决了这个问题:
protected $casts = [
'name' => 'string',
'ects' => 'integer',
'studies' => 'array'
];
可以查看文档看起来您正在对整个
雄辩的集合进行json编码
,当您使用get()
方法()时返回该集合
从laravel文档:
json方法将自动将内容类型头设置为application/json,,并使用json_encode PHP函数将给定数组转换为json:
因此,本质上,您正在使用
json_encode()
将整个集合转换为json,这将假定您的json
字段是一个字符串,因此已将其转义。您给了我一个开始研究的位置,可以在编辑中看到解决方案。感谢此解决方案,您也遇到了同样的问题,casts工作正常。