【发布时间】:2013-07-01 10:25:15
【问题描述】:
我正在尝试使用批量分配 Eloquent 功能创建实体...
$new = new Contact(Input::all());
$new->save();
问题在于,这样一来,每个字段都填充了一个空字符串,而不是我预期的 null 值。
我目前正在开发系统,但仍有一些表列没有定义,这就是为什么使用这种方法,以避免将每个新字段添加到 $fillable 数组和 new Contact(array(...));...
而且我在这个表中有大约 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() 过滤器中解决了这个问题。
更新过滤器有点乱。我最终会这样做:
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,数据库会因为找不到外键“”而抛出错误。
完美运行。有什么意见吗?
【问题讨论】:
-
把这个放在一行中...
Contact::create(Input::all())ftw. -
我不是用这种方式得到空值吗?我认为它的作用与
$new = new Contact(Input::all());相同