【发布时间】:2014-04-10 19:17:06
【问题描述】:
我正在尝试允许管理员从具有列标题、列类型和目标表字段的表单在 sql 表中创建新列。我确信我没有以最优雅的方式执行此操作,但我正在尝试使用该框架,而不是让每个人都因为直接查询数据库而殴打我。我创建了以下几乎完全可以工作的控制器,但是,当我尝试使用 $new_column 而不是硬编码字符串时,我得到一个未定义的变量异常。
//Capture variables from view
$type = Input::get('type');
$table_name = Input::get('table');
$proposed_name = Input::get('name');
//Convert proposed name into useable column name
$new_column = strtolower(str_replace(' ', '_', (preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $proposed_name))));
if($type == 'string')
{Schema::table($table_name, function($table){$table->string($new_column);});}
elseif($type == 'date')
{Schema::table($table_name, function($table){$table->date($new_column);});}
...
//Flash Success
$message = 'Variable "' . $proposed_name . '"" has been successfully created.';
Session::flash('flash_success', $message);
return Redirect::action('VariableManagerController@getIndex');
有没有办法通过 Larval 框架完成这项工作,或者我应该只对数据库进行原始查询?
为了记录,这将使用 try catch 块,但这只会进一步混淆上面的代码。
【问题讨论】:
-
您的代码看起来不错,我认为这应该可以。对于该错误,在
$new_column定义和它的使用之间一定存在其他问题。