我有一個驗證規則,看起來像這樣:驗證:如何設置不需要「空」字段時輸入爲空
$rules = ['target' => 'numeric'];
這不是必填字段。如果在輸入中沒有指定一個值(即Input :: get('target')==''),我希望該字段在數據庫中設置爲NULL。
當前上述規則通過,並且在沒有數字輸入的情況下,它將在數據庫中設置爲0。
什麼是最好的解決方案?
我有一個驗證規則,看起來像這樣:驗證:如何設置不需要「空」字段時輸入爲空
$rules = ['target' => 'numeric'];
這不是必填字段。如果在輸入中沒有指定一個值(即Input :: get('target')==''),我希望該字段在數據庫中設置爲NULL。
當前上述規則通過,並且在沒有數字輸入的情況下,它將在數據庫中設置爲0。
什麼是最好的解決方案?
只需在調用save()
之前將null
值分配給適當的模型屬性,您就可以在Laravel中將字段設置爲null
。
if(! Input::get('target')){
$eloquent_model->target = null;
}
$eloquent_model->save();
但是,如果您想要在多個模型中插入空值,您可以創建基礎模型並通過其他模型繼承基礎模型。
class BaseModel extends Eloquent {
public static function boot()
{
parent::boot();
static::creating(function($model) {
static::setNullWhenEmpty($model);
return true;
});
}
private static function setNullWhenEmpty($model)
{
foreach ($model->toArray() as $name => $value) {
if (empty($value)) {
$model->{$name} = null;
}
}
}
}
現在,所有空字段將被自動設置爲null
和你沒有檢查之前保存。
我不認爲這是一個laravel的問題,你必須添加標籤mysql ... 改變表添加Null作爲默認值..目前,如果您傳遞空白值,它會添加0,因爲默認它不爲NULL,並顯示
Warning: #1366 Incorrect integer value: '' for column 'target' at row 1.
這裏是改變查詢..
ALTER TABLE `table` CHANGE `target` `target` INT(11) NULL
上面的查詢運行後,target
將接受NULL值,而不是0!
在這種情況下,我喜歡使用存取器:
public function setTargetAttribute($target){
$this->attributes['target'] = $target ?: null;
}
最乾淨的選項,如果你問我 – mauricehofman
我的解決辦法是這樣的(Laravel 5.2):
//Model.php
public function nullIfBlank($field) {
return trim($field) !== '' ? $field : null;
}
//你的自定義模型擴展Model.php
public function setTargetAttribute($target) {
$this->attributes['target'] = $this->nullIfBlank($target);
}
注意如上所述命名你的setter(mutator),lowerCamelCase和magic會發生。
在數據庫結構中,該列的默認值應該是NULL,這很有用)否則,您將始終看到一個空值,而不是「NULL」。 – Pathros