【问题标题】:How to bind model from different fieldname如何从不同的字段名绑定模型
【发布时间】:2015-03-12 07:59:37
【问题描述】:

我尝试在 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() !!}

【问题讨论】:

  • 据我所知,你不能直接这样做,我宁愿在视图中更改名称以匹配模型的名称。
  • 有趣:为什么不能使用下划线名称?

标签: php forms laravel model-binding laravel-5


【解决方案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(); 
}

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2014-01-19
    相关资源
    最近更新 更多