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

标签 php mysql laravel

我正在使用 Laravel 和 eloquent 以及 mysql 数据库。

我的数据库中有一个 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 捕获这种格式的数据?

最佳答案

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

关于php - 如何使用 Laravel 将 mysql json 字段转换为 javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506403/

相关文章:

php - Laravel 将 setlocale 与 carbon 一起使用的最佳方式

javascript - 如何修复 500(内部服务器错误)Vue js - Laravel(已编辑)

php - Laravel elixer 版本控制(缓存破坏器)多服务器

php - 有没有办法可以将 "httpOnly"参数传递给 PHP 的 setcookie 函数,而不传递所有 "extra"参数?

mysql - 确定 M :N database system 中未使用的值

php - PHP 脚本可以发送到 MySQL TEXT 字段的最大数据量?

php - 如何从 Laravel Horizo​​n 中的 Redis 队列重试所有失败的作业

php - PHP:设置 session 时,数据未插入数据库吗?

php - 使用 PHP 删除打开的 HTML 注释

php - Laravel - 模型自引用 belongsToMany 与其他关系和具有多个限制的查询