空字符串而不是空值 [英] Empty string instead of null values Eloquent

查看:93
本文介绍了空字符串而不是空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用大量分配雄辩功能创建实体...

I'm trying to create entities using mass-assignment Eloquent feature...

$new = new Contact(Input::all());
$new->save();

问题是这样,每个字段都用空字符串填充,而不是我期望的null值.

The problem's that this way, every field's filled out with an empty string instead of null values as I expected.

我目前正在开发系统,但仍未定义一些表列,这就是使用此方法的原因,以避免将每个新字段都添加到$fillable数组和new Contact(array(...)); ...

I'm currently developing the system and still some table columns're not defined, that's why using this method, to avoid adding every new field to $fillable array and to a new Contact(array(...));...

我在此表中也有大约20个字段,因此拥有一个数组,例如

Also I've around 20 fields in this table, so It'd be a bit ugly to have an array such as

$new = new Contact(array(
    'salutation' => Input::get('salutation'),
    'first_name' => Input::get('first_name'),
    'last_name'  => Input::get('last_name'),
    'company_id' => Input::get('company_id'),
    'city' => ...
    ...
));

有关如何执行此操作或修复操作的任何提示?

Any tips of how to do this or fix?

更新到目前为止,我已经在App::before()过滤器中执行array_filter了.

Update By now I've sorted out this doing the array_filter in the App::before() filter.

更新在过滤器中有些混乱.我最终做了:

Update In filter was a bit mess. I end up doing:

public static function allEmptyIdsToNull()
{
    $input = Input::all();

    $result = preg_grep_keys ( '/_id$/' , $input );

    $nulledResults = array_map(function($item) {
        if (empty($item))
            return null;

        return $item;
    }, $result);

    return array_merge($input, $nulledResults);
}

在我的functions.php中.

And in my functions.php.

if ( ! function_exists('preg_grep_keys'))
{
    /**
    * This function gets does the same as preg_grep but applies the regex
    * to the array keys instead to the array values as this last does.
    * Returns an array containing only the keys that match the exp.
    * 
    * @author Daniel Klein
    * 
    * @param  string  $pattern
    * @param  array  $input
    * @param  integer $flags
    * @return array
    */
    function preg_grep_keys($pattern, array $input, $flags = 0) {
        return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
    }
}

现在,仅适用于以"_id"结尾的字段.这是我最大的问题,因为如果关系不是NULL,则数据库将抛出错误,因为找不到外键".

By now only working with fields that ends with "_id". This is my biggest problem as if a relationship is not NULL, the database will throw an error as the foreign key "" cannot be found.

完美.有任何评论吗?

推荐答案

使用模型保存"事件查找空模型并将其显式设置为null.在此示例中,项目"是我的模型的名称.将其放在一个辅助函数中,并将其连接到所有模型.

Use the model 'saving' event to look for empty models and explicitly set them to null. 'Project' is the name of my model in this example. Put this in a helper function and wire it up to all your models.

Project::saving(function($model) {
    foreach ($model->toArray() as $name => $value) {
        if (empty($value)) {
            $model->{$name} = null;
        }
    }

    return true;
});

更新LARAVEL 5(2016年4月11日)

UPDATE FOR LARAVEL 5 (April 11 2016)

除了在将数据发送到数据库之前清除数据之外,我还最终创建了一个Http Middleware来清除来自http请求的输入数据.

I also ended up creating an Http Middleware to cleanup the input data from the http request, in addition to cleaning up the data before it is sent to the database.

class InputCleanup
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->input();

        array_walk_recursive($input, function(&$value) {

            if (is_string($value)) {
                $value = StringHelper::trimNull($value);
            }
        });

        $request->replace($input);

        return $next($request);
    }
}

这篇关于空字符串而不是空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆