我正在尝试使用批量分配 Eloquent 功能创建实体...
$new = new Contact(Input::all());
$new->save();
问题是这样,每个字段都用空字符串而不是我预期的 null
值填充。
我目前正在开发系统,但仍有一些表列未定义,这就是为什么使用此方法,以避免将每个新字段添加到 $fillable
数组和 new联系人(数组(...));
...
而且我在这个表中有大约 20 个字段,所以如果有一个像这样的数组会有点难看
$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' => ...
...
));
关于如何执行此操作或修复的任何提示?
更新 到目前为止,我已经通过 App::before()
过滤器中的 array_filter 解决了这个问题。
更新 过滤器有点乱。我最终做了:
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 中。
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
,数据库将抛出错误,因为找不到外键“”。
工作完美。有什么意见吗?
最佳答案
我自己寻找过这个问题的答案,我能想到的最接近的答案是使用 Mutators ( http://laravel.com/docs/eloquent#accessors-and-mutators )。
通过为模型中的外键字段添加一个(神奇的!)Mutator 方法解决了同样的问题:
public function setHeaderImageIdAttribute($value)
{
$this->attributes['header_image_id'] = $value ?: null;
}
对于具有大量外键的表,这可能会有点笨重,但这是我发现的处理此问题的最“内置”方法。好处是它很神奇,所以您只需创建方法即可。
更新 -- Laravel 5.4 及更高版本
从 Laravel 5.4 开始,\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class
中间件会在收到请求时处理这个问题。在我上面的示例中,如果请求包含“header_image_id”的空字符串值,此中间件会自动将其转换为 null
,然后我才能将其分配给我的模型。
关于php - 空字符串而不是空值 Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17452923/