我正在尝试允许管理员通过一个表单创建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');
这个问题能否通过Laravel框架来解决,还是应该直接对数据库进行原始查询?
值得一提的是,这将使用try catch块,但这只会让上面的代码更加混乱。
$new_column
定义和使用之间发生了其他故障。 - bishop