具有json类型字段的Laravel数据库在返回值时添加\"

And*_*rej 5 php json laravel laravel-5

我已经删除了Laravel 5文档,我已经看到它支持数据库中的json类型字段,但我注意到了非常奇怪的行为.

这是我的表:

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');
});
Run Code Online (Sandbox Code Playgroud)

然后我用以下方法播种数据库:

Subject::create(['name' => 'Programming 1', 
'ects' => '0',
'studies' => '{"program":"Computer Science","year":"1"}']);
Run Code Online (Sandbox Code Playgroud)

服务器响应看起来像这样:

{
     "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
     }
}
Run Code Online (Sandbox Code Playgroud)

请注意\"在响应字段研究中,laravel为我生成的"pivot"字段正确构造,并且也是json类型字段.

当我查看phpMyAdmin时,研究领域的价值看起来很正常.(没有\")

我的响应服务器代码:

$subjects = Profesor::find($id)->subjets()->get();
return response()->json($subjects);
Run Code Online (Sandbox Code Playgroud)

我是否正确播种了数据库,或者问题是我在服务器上返回值?

我知道我可以在客户端解决这个问题,删除符号"\",但这是我的最后一个选项,因为它不够干净.

编辑:

我通过在我的Model类中添加一个数组转换来解决它:

protected $casts = [
     'name' => 'string',
     'ects' => 'integer',
     'studies' => 'array'
];
Run Code Online (Sandbox Code Playgroud)

文档可以在这里看到

cra*_*g_h 2

看起来您正在对整个 json 进行编码eloquent collection,当您使用该方法时会返回该get()值(http://laravel.com/docs/5.1/eloquent-collections)。

来自 Laravel 文档:

json 方法会自动将 Content-Type 标头设置为 application/json,并使用 json_encode PHP 函数将给定数组转换为 JSON

因此,本质上,您将整个集合转换为 json,使用json_encode()它会假设您的json字段是一个字符串,因此已对其进行转义。