【发布时间】:2013-12-18 21:32:56
【问题描述】:
当您在表中创建新列时,您可以使用 ->after('column name') 来指示它的去向。如何创建以我想要的正确顺序重新排序列的迁移?
【问题讨论】:
当您在表中创建新列时,您可以使用 ->after('column name') 来指示它的去向。如何创建以我想要的正确顺序重新排序列的迁移?
【问题讨论】:
试试这个,希望它能帮助你找到正确的解决方案:
public function up()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
public function down()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
【讨论】:
foo DATE 中的 DATE 应更改为您正在使用的任何数据类型。
DB::statement("ALTER TABLE example MODIFY COLUMN foo VARCHAR(32) AFTER bar");
alter table student_ieps modify column iep_topic_id bigint unsigned after student_id
如果您想在不破坏数据的情况下执行此操作,则可以在进行架构更新的同时迁移数据:
use DB;
public function up()
{
//Give the moving column a temporary name:
Schema::table('users', function($table)
{
$table->renameColumn('name', 'name_old');
});
//Add a new column with the regular name:
Schema::table('users', function(Blueprint $table)
{
$table->string('name')->after('city');
});
//Copy the data across to the new column:
DB::table('users')->update([
'name' => DB::raw('name_old')
]);
//Remove the old column:
Schema::table('users', function(Blueprint $table)
{
$table->dropColumn('name_old');
});
}
【讨论】:
我建议使用 DB::query('.. raw sql query ..');并使用答案“How to move columns in a MySQL table?”中的查询
【讨论】:
试试这个
public function up()
{
DB::statement("ALTER TABLE example CHANGE foo foo DATA_TYPE DATA_ATTRIBUTE(s) AFTER bar");
DB::statement("ALTER TABLE example CHANGE foo foo INT(10) UNSIGNED NOT NULL AFTER bar");
}
或者如果你懒得搞清楚SQL,你可以访问你的phpMyAdmin,点击你的数据库,点击你的表,点击结构选项卡,除了你要移动的列,点击更改按钮,编辑最后的移动column 列,单击保存按钮,然后复制 SQL。
【讨论】:
仅在您尚未启动应用(即尚未被任何真实用户使用)时使用以下解决方案,因为以下解决方案将删除该列以及存储在其中的所有数据,并将在您确定的列之后创建一个具有相同名称的新空列。
假设您的列名是address,并且您想重新排列它的位置,使其位于另一个名为city 的列之后,而您的表名是employees。
在你的终端输入下一个命令:
php artisan migrate:make reorganize_order_of_column_address --table=employees
您只能根据需要更改reorganize_order_of_column_address 和employees,但保持命令的其余部分不变。
这将在app/database/migrations 文件夹中生成一个迁移文件,打开它并将您的代码放入up() 函数中,如下所示:
public function up()
{
Schema::table('employees', function(Blueprint $table)
{
$table->dropColumn("address");
});
Schema::table('employees', function(Blueprint $table)
{
$table->string('address')->after("city");
});
}
【讨论】: