Laravel Eloquent Model toJson方法不能递归地工作

时间:2017-10-18 11:55:22

标签: php laravel eloquent

我已阅读docs此方法应该是递归的,但它不适用于模型属性:

表格迁移

Schema::create('test', function (Blueprint $table) {

    $table->increments('id');
    $table->string('test');
    $table->json('testJson')->nullable();

});

执行

Test::findOrFail($id)->get()->toJson();

响应

{
 id:0,
 test:'',
 testJson:'[{}]' //as string! i need array of objects.
}

2 个答案:

答案 0 :(得分:1)

如果您需要使用它而不仅仅是观看它,您可以随时执行此操作:

$test = Test::findOrFail($id)->get()->toJson();

并使用json_decode($test->testJson);将其作为数组。

或者如果你真的想要它代替json字符串,请使用:

$test = Test::findOrFail($id)->get()->toJson();

$test['testJson'] = json_decode($test->testJson)

答案 1 :(得分:0)

我在雄辩的模特中发现了attribute-casting

在模型中,您可以指定在更新或检索属性时如何转换属性。

<强>模型

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

<强>效应初探

{
 id:0,
 test:'',
 testJson:[{}] //as json!.
}

这有点奇怪,应该通过json类型的列自动完成。