在Laravel中动态创建新列

3

我正在尝试允许管理员通过一个表单创建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
1个回答

0
$alldata=Input::all();

$table_name = Input::get('table');

Schema::table($table_name, function($table) use ($alldata)
{
   $colname=$alldata['name'];
   $coltype=$alldata['type'];
   $table->$coltype($colname);});
}

2
虽然您的回答可能解决了问题,但如果您能提供问题的描述以及您的回答是如何解决它的,那就更好了。这是进一步改善当前和未来回答的建议。 - Luís Cruz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接