我有一些字段在MySQL默认为NULL。例如,在下面的代码片段中,name是必需的,而不是null,但是name_abbrev、email_general和description都是可空的,并且在数据库中默认设置为null。但在Laravel中,通过表输入数据大部分都不起作用。如果我插入一行,只有名称,其他所有内容都留空,那么名称当然会正确输入,email_general输入NULL,但是其他两个可空字段发送空字符串而不是NULL。如果我随后更新该行,比如通过更改名称,那么更新也会将email_general的NULL更改为空字符串。如果我手动更改数据库行中可空字段的值,从空字符串到NULL,当我更新行(仍然使所有空字段为空)时,它将所有NULL字段更改为空字符串。我找不出我做错了什么。为什么它不会输入NULL(除了在一个字段,这是编码完全相同的其他),为什么更新改变,甚至该字段为空字符串?
控制器:
public function store()
{
$component = new Component;
$component->name = Input::get('name');
$component->name_abbrev = Input::get('name_abbrev');
$component->email_general = Input::get('email_general');
$component->description = Input::get('description'); ...
$component->save();
return Redirect::route('components.index');
}
public function update($id)
{
$component = $this->component->find($id);
$component->name = Input::get('name');
$component->name_abbrev = Input::get('name_abbrev');
$component->email_general = Input::get('email_general');
$component->description = Input::get('description'); ...
$component->save();
return Redirect::route('components.index');
}
create.blade.php:
{{ Form::open(['route' => 'components.store']) }}
<div class="required">
{{ Form::label('name','Name:') }}
{{ Form::text('name') }}
{{ $errors->first('name') }}
</div>
<div>
{{ Form::label('name_abbrev','Abbreviation:') }}
{{ Form::text('name_abbrev', NULL) }}
</div>
<div>
{{ Form::label('email','General Email:') }}
{{ Form::text('email',NULL) }}
</div>
<div>
{{ Form::label('description','Description:') }}
{{ Form::textarea('description',NULL,['size' => '26x3']) }}
</div> ...
<div>
{{ Form::submit('Add New Component', array('class'=>'button')) }}
</div>
{{ Form::close() }}
edit.blade.php:
{{ Form::model($component, array('method'=>'put','route'=>array('components.update', $component->id))) }}
<div class="required">
{{ Form::label('name','Name:') }}
{{ Form::text('name') }}
{{ $errors->first('name') }}
</div>
<div>
{{ Form::label('name_abbrev','Abbreviation:') }}
{{ Form::text('name_abbrev', NULL) }}
</div>
<div>
{{ Form::label('email_general','General Email:') }}
{{ Form::text('email_general', NULL) }}
</div
<div>
{{ Form::label('description','Description:') }}
{{ Form::textarea('description',NULL,['size' => '26x3']) }}
</div> ...
<div>
{{ Form::submit('Update Component', array('class'=>'button')) }}
</div>
{{ Form::close() }}
非常感谢!这应该很容易,但由于某些原因,它不是。
如果您确实需要在某些列上设置null,我建议您使用Mutators:
Laravel 3: http://three.laravel.com/docs/database/eloquent#getter-and-setter-methods
Laravel 4: http://laravel.com/docs/eloquent#accessors-and-mutators
所以如果新值是一个空字符串(!