我试图创建使用质量分配的优秀功能的实体…
$new = new Contact(Input::all());
$new->save();
问题是,这样,每个字段都填充一个空字符串,而不是我预期的空值。
我正在开发系统,仍然没有定义一些表列,这就是为什么使用这种方法,以避免将每个新字段添加到$ fillable数组和新的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,数据库会抛出一个错误,因为找不到外键“”。
工作完美。任何意见?