gpt4 book ai didi

mysql - 在 Laravel 中动态创建新列

转载 作者:行者123 更新时间:2023-11-29 01:03:25 24 4
gpt4 key购买 nike

我正在尝试允许管理员从具有列标题、列类型和目标表的字段的表单中在 sql 表中创建新列。我确定我没有以最优雅的方式执行此操作,但我正在尝试使用该框架,而不是让每个人都因为直接查询数据库而殴打我。我创建了以下几乎完全可用的 Controller ,但是,当我尝试使用 $new_column 而不是硬编码字符串时,我得到了一个 undefined variable 异常。

//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 block ,但这只会进一步混淆上面的代码。

最佳答案

$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);});
}

关于mysql - 在 Laravel 中动态创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com