donkey199024 2017-04-26 07: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 08: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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部