Eloquent将缺少的属性保存为空字符串而不是NULL

时间:2014-02-28 20:34:50

标签: mysql laravel laravel-4 eloquent

当我尝试将具有缺少属性的模型保存到非NULL数据库字段时,我不希望应用程序对此保持安静,我希望它能够静静地尖叫。但对于那些雄辩的空字符串来说,这很好。

为什么MyModel::create([])成功?

1 个答案:

答案 0 :(得分:0)

class BaseModel extends Eloquent {

    public static function boot()
    {
        parent::boot();

        static::creating(function($model) {
            static::setNullWhenEmpty($model);
            return true;
        });
    }

    private static function setNullWhenEmpty($model)
    {
        foreach ($model->toArray() as $name => $value) {
            if (empty($value)) {
                $model->{$name} = null;
            }
        }
    }
}

信用: Set fields to null instead of empty value to avoid problems with nullable foreign keys