我想使用批量赋值的 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()
过滤器中使用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
,数据库将抛出错误,因为找不到外键""。
完美运作。有任何评论吗?
Contact::create(Input::all())
赢了。 - Rob W$new = new Contact(Input::all());
是一样的。 - Israel Ortuño