我尝试在 edit.blade.php 中进行模型绑定,但是,数据库host_firstname
中的字段名与表单host-firstname
的字段名不同
因此,当我们运行时,数据库中的数据不会显示在字段中。 (我也不想在我的视图中更改数据字段名称)
我对Laravel很新,我不确定如何在模型中设置默认键名以使其正常工作。有没有人对此有任何解决方案?
数据库架构
family_general_id int(10) unsigned NOT NULL AUTO_INCREMENT,
host_firstname varchar(255) COLLATE utf8_unicode_ci NOT NULL,
host_lastname varchar(255) COLLATE utf8_unicode_ci NOT NULL,
edit.blade.php
{!! Form::model($survey, ['method' => 'PATCH', 'url' => 'surveys/' . $survey->family_general_id]) !!}
<!-- Host-firstname Form Input-->
<div class="form-group">
{!! Form::label('host-firstname', 'Firstname:') !!}
{!! Form::text('host-firstname', null, ['class' => 'form-control']) !!}
</div>
<!-- Host-lastname Form Input-->
<div class="form-group">
{!! Form::label('host-lastname', 'Lastname:') !!}
{!! Form::text('host-lastname', null, ['class' => 'form-control']) !!}
</div>
{!! Form::close() !!}
答案 0 :(得分:1)
我不确定此刻是否可行。
我看了一下Illuminate / Html / FormBuilder,你可以看到transformKey()
仅适用于under_scores
/**
* Get the model value that should be assigned to the field.
*
* @param string $name
* @return string
*/
protected function getModelValueAttribute($name)
{
if (is_object($this->model))
{
return object_get($this->model, $this->transformKey($name));
}
elseif (is_array($this->model))
{
return array_get($this->model, $this->transformKey($name));
}
}
protected function transformKey($key)
{
return str_replace(array('.', '[]', '[', ']'), array('_', '', '.', ''), $key);
}
我可以建议使用基本laravel表单构建器的解决方案,因为这是一个特例:
{!! Form::open(['method' => 'PATCH', 'url' => 'surveys/' . $survey->family_general_id]) !!}
<!-- Host-firstname Form Input-->
<div class="form-group">
{!! Form::label('host-firstname', 'Firstname:') !!}
{!! Form::text('host-firstname', null, ['class' => 'form-control']) !!}
</div>
<!-- Host-lastname Form Input-->
<div class="form-group">
{!! Form::label('host-lastname', 'Lastname:') !!}
{!! Form::text('host-lastname', null, ['class' => 'form-control']) !!}
</div>
{!! Form::close() !!}
然后执行以下操作:
class SurveyController extends Controller
{
//after validation
$host_firstname = Input::get('host-firstname');
//send this to your database $host_firstname
$survey = new Survey;
$survey->host_firstname = $host_firstname;
$survey->save();
}