繁体   English   中英

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

[英]How to convert a mysql json field to a javascript Object with laravel?

我正在使用带有 eloquent 和 mysql 数据库的 laravel。

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

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 路由上的数据时:

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

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

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}",
    },

但我需要它们采用这种格式:

"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 捕获这种格式的数据?

在处理存储为序列化 JSON 的列时,数组转换类型特别有用。 例如,如果您的数据库有一个包含序列化 JSON 的 JSON 或 TEXT 字段类型,当您在 Eloquent 模型上访问它时,将数组转换添加到该属性将自动将属性反序列化为 PHP 数组:

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 数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM