Eloquent Model toJson()包含空属性?

时间:2017-04-26 15:39:02

标签: php json laravel eloquent

如何打印具有空值的Laravel Eloquent模型?我希望获得一个新的Question对象,以包含所有字段,只需使用null,而是打印[]

var app = new Vue({
    el: "#survey-form",

    data: function() {
        return {
            survey: {!! $survey !!}
        };
    },

    methods: {
        add: function() {
            return this.survey.questions.push({!! new App\Question !!});
        }
    }
});

鉴于App\Questionidsurvey_idtext字段,

(new App\Question())->toJson()打印[]

如何打印{"id": null, "survey_id": null, "text": null}

修改

对于那些想知道的人,我正在尝试获取问题的结构,以便在模型结构发生变化时我不必担心在模板中更改JSON的结构。我知道我可以用

轻松地对结构进行硬编码
return this.survey.questions.push({"id": null, "survey_id": null, "text": null});

但是,每次将一列添加到问题表中时,我都必须记住在模板文件中更改它。依靠{!! new App\Question !!},我希望它会自动反映结构。

1 个答案:

答案 0 :(得分:1)

在查询数据库并从查询中获取返回的属性之前,模型不知道列。这就是你的新实例没有任何属性的原因。

您需要手动填写属性,但可以使用Laravel获取列名称。

您的代码将类似于:

this.myService.dataUpdated.subscribe
      (
        (data: someObject) => {
          // Do something...
        }
      )

将所有这些组合成一行:

$question = new \App\Question();

// get the columns from the questions table
$fields = \Schema::getColumnListing($question->getTable());

// create an array where the keys are the field names and the values are null
$nullFields = array_fill_keys($fields, null);

// force fill the model instance with the null fields
$question->forceFill($nullFields);

// get your json
$json = $question->toJson();

而且,如果你不喜欢第二个“新”实例,你可以使用(new \App\Question())->forceFill(array_fill_keys(\Schema::getColumnListing((new \App\Question())->getTable()), null))->toJson(); 帮助器(假设你在> = 5.3):

tap