验证:如何在输入为空时设置不需要"null"的字段

mtm*_*ald 8 laravel laravel-4

我有一个如下所示的验证规则:

$rules = ['target' => 'numeric'];
Run Code Online (Sandbox Code Playgroud)

这不是必填字段.如果未在输入中指定值(即Input :: get('target')==''),我希望在数据库中将该字段设置为NULL.

目前,上述规则通过,并且在没有数字输入的情况下,它在数据库中设置为0.

什么是最好的解决方案?

Wal*_*mar 9

null只需null在调用之前将值赋给适当的模型属性,就可以像在Laravel中一样设置字段save().

if(! Input::get('target') ){
    $eloquent_model->target = null;
}

$eloquent_model->save();
Run Code Online (Sandbox Code Playgroud)

但是,如果要在多个模型中插入空值,则可以创建基本模型并由所有其他模型继承它.

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在所有空字段都将null自动设置,您无需在保存之前进行检查.

参考.


Pie*_*rre 8

在这种情况下,我喜欢使用mutators:

public function setTargetAttribute($target){

  $this->attributes['target'] = $target ?: null;

}
Run Code Online (Sandbox Code Playgroud)