donkey199024 2017-04-26 15:39
浏览 44
已采纳

Eloquent Model toJson()包含空属性?

How can I print a Laravel Eloquent Model with null values? I want to get a new Question object to include all the fields, just with null, but instead, it prints a [].

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

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

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

Given that App\Question has id, survey_id, and text fields,

(new App\Question())->toJson() prints [].

How Can I make it print {"id": null, "survey_id": null, "text": null}?

Edit

For those wondering, I'm trying to get the structure of a question so that I don't have to worry about changing the structure of the JSON in the template if the model structure changes. I know I could easily hardcode the structure with

return this.survey.questions.push({"id": null, "survey_id": null, "text": null});

but with that, every time a column is added to the questions table, I'll have to remember to change that in the template file too. By relying on {!! new App\Question !!}, I hoped it would reflect the structure automatically.

  • 写回答

1条回答 默认 最新

  • douke6027 2017-04-26 16:18
    关注

    The model doesn't know about the columns until it queries the database and gets the returned attributes from the query. That is why your new instance doesn't have any attributes.

    You will need to fill in the attributes manually, but you can use Laravel to get the column names.

    Your code will look something like:

    $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();
    

    To combine that all into one line:

    (new \App\Question())->forceFill(array_fill_keys(\Schema::getColumnListing((new \App\Question())->getTable()), null))->toJson();
    

    And, if you don't like that second "new" instance, you can use the tap helper (assuming you're on >=5.3):

    tap(new \App\Question(), function ($question) { $question->forceFill(array_fill_keys(Schema::getColumnListing($question->getTable()), null)); })->toJson()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里