一括割り当て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' => ...
...
));
これを行う方法または修正する方法のヒントはありますか?
更新これまでに、フィルターで array_filter を実行してこれを整理しましたApp::before()
。
Update Inフィルターは少し混乱していました。私はやってしまう:
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
場合、データベースは外部キー "" が見つからないためエラーをスローします。
完璧に動作します。任意のコメント?