【问题标题】:What's the correct way to provide default values for Laravel model fields outside of MySQL?为 MySQL 之外的 Laravel 模型字段提供默认值的正确方法是什么?
【发布时间】:2015-03-05 16:37:33
【问题描述】:

我有一个 Laravel 模型,它有多个在数据库中默认为 NULL 的字段,并且由于遗留原因不能轻易更改。我希望始终将这些作为空字符串返回,例如,从我的路由返回 JSON 时。是否有一种“标准”方式来以某种方式在模型中定义默认值?

另一种情况可能是某个字段在返回之前总是需要对其进行一些处理,这也可以用类似的方式定义吗?谢谢。

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    默认值

    您可以使用$attributes 属性指定默认值:

    class MyModel extends Eloquent {
        protected $attributes = array(
            'foo' => 'bar'
        );
    }
    

    但是我认为这仍然会被数据库中的NULL 覆盖。 $attributes 的用例是在创建和插入新记录时。

    操作 JSON / 数组输出

    要在将模型转换为 JSON / 之前更改模型,您可以在模型中覆盖 toArray()

    public function toArray(){
        $array = parent::toArray();
        foreach($array as &$value){
            if($value == null){
                $value = '';
            }
        }
        return $array;
    }
    

    带有访问器的自定义属性

    如果您有某些需要特殊处理的字段(例如格式化日期、连接两个属性),您可以使用accessor

    public function getFullNameAttribute(){
        return $this->attributes['firstname'].' '.$this->attributes['lastname'];
    }
    

    现在您可以通过$model->full_name(或$model->fullName,随心所欲)访问它

    最后,要将其添加到 JSON / 数组输出,请使用 $appends

    protected $appends = array('full_name');
    

    【讨论】:

    • 很好的答案,谢谢。这些的一些组合应该可以解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2016-11-19
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多