如何使用laravel将mysql json字段转换为javascript对象?

问题描述:

我使用的是雄辩的laravel和mysql数据库.

I'm using laravel with eloquent and a mysql database.

我的数据库中有一个JSON字段:

There is a JSON field in my database:

class CreateJogoDetalhesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tableX', function (Blueprint $table) {
            $table->increments('id');
            [... others ...]
            $table->json('numbers');
    }
[...]

当我在模型/api路线上检索数据时:

When I retrieve the data on my model/api route:

Route::middleware('cors:api')->get('/MYROUTE', function (Request $request) {
    $resource= Tablex::with('tb1','tb2','tb3')->get();
    return $resource->toJson();
});

我的mysql json字段带有字符串格式:

My mysql json field comes with a string format:

tableX": {
      "id": 1,
      "name": "foo",
      "values": "{\"6\": 3.5, \"7\": 24.5, \"8\": 24.5, \"9\": 24.5, \"10\": 24.5, \"11\": 24.5, \"12\": 24.5, \"13\": 24.5, \"14\": 24.5, \"15\": 24.5}",
    },

但是我需要使用以下格式:

But I need them on this format:

"tableX": {
      "id": 1,
      "name": "foo",
      "values": {
        "6": 3.5,
        "7": 24.5,
        "8": 24.5,
        "9": 24.5,
        "10": 24.5,
        "11": 24.5,
        "12": 24.5,
        "13": 24.5,
        "14": 24.5,
        "15": 24.5
      },

我如何要求laravel捕获这种格式的数据?

How can I ask to laravel catch the data on this format?

在处理列时,数组强制转换类型特别有用 存储为序列化的JSON.例如,如果您的数据库具有 包含序列化JSON的JSON或TEXT字段类型,添加 转换为该属性的数组将自动反序列化 在Eloquent模型*问PHP数组时将属性赋给它:

The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'values' => 'array',
    ];
}

https://laravel.com/docs/5.7/eloquent-mutators#array-and-json-casting

这会将其转换为PHP端的数组,并在Laravel序列化模型时正确包含JSON数据.

This will convert it to an array on the PHP side and will properly include the JSON data when Laravel serializes the model.