【问题标题】:Eloquent Model toJson() Include Null Properties?雄辩的模型 toJson() 包括空属性?
【发布时间】:2017-09-24 03:01:14
【问题描述】:

如何打印具有空值的 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\Question 具有idsurvey_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 !!},我希望它能自动反映结构。

【问题讨论】:

    标签: php json laravel eloquent


    【解决方案1】:

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

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

    您的代码将类似于:

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

    而且,如果您不喜欢第二个“新”实例,您可以使用 tap 助手(假设您使用 >=5.3):

    tap(new \App\Question(), function ($question) { $question->forceFill(array_fill_keys(Schema::getColumnListing($question->getTable()), null)); })->toJson()
    

    【讨论】:

    • 甜蜜!当我想将其作为$this->forceFill( array_fill_keys(\Schema::getColumnListing($this->getTable()), null) ); 放入我的构造函数时,是否有任何我没有想到的问题
    • @Goldentoa11 是的。您可能会不小心将数据库中的某些字段清空。想象以下代码:\App\Question::select('id')->find(1)->save();。该代码会无意中尝试清空除 id 之外的所有字段。我建议创建一个新函数来实现该功能(例如empty()),因此您的代码看起来像(new \App\Question)->empty()->toJson()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 2021-08-11
    • 2017-11-19
    • 2016-07-21
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多