我想在 Laravel 中更改两个表的名称,那么是需要手动更改表名还是可以通过迁移实现。
从文档中 laravel.com/docs/5.1/migrations#renaming-and-dropping-tables
要更改表名,您可以执行以下操作:
Schema::rename($currentTableName, $newTableName);
您可以使用drop
或dropIfExists
方法来删除现有的表:
Schema::drop('users');
Schema::dropIfExists('users');
只需要将这个添加到迁移中,它应该就可以工作了。
你可以像这样重命名表
Schema::rename('old_table', 'new_table');
但是,如果你有外键
、索引
和唯一约束
,重命名后你需要小心,因为你将无法删除它们。
就像这样。
Schema::table('new_table', function (Blueprint $table) {
$table->dropForeign(['transaction_id']);
});
因为它们将具有旧名称,这些名称中包含表名。
因此,我建议先删除 外键
和其他内容。
Schema::table('old_table', function (Blueprint $table) {
$table->dropForeign(['transaction_id']);
});
Schema::rename('old_table', 'new_table');
Schema::table('new_table', function (Blueprint $table) {
$table->foreign('transaction_id')->references('id')->on('transactions');
});
首先,使用CLI命令创建迁移:
php artisan make:migration rename_table
现在,在新迁移类的up方法中,使用rename方法更改表名:
Schema::rename('old_table_name', 'new_table_name');
接下来,执行迁移命令:
php artisan migrate
要重命名一个已经存在的数据库表,请使用rename方法:
Schema::rename($from, $to);
要删除现有的表,您可以使用 drop 或 dropIfExists
方法:
Schema::drop('users');
Schema::dropIfExists('users');
首先,运行以下命令在终端中创建迁移文件以重命名表:
php artisan make:migration rename_old_name_to_new_name_table
然后在 up 方法中,您应该有以下内容:
public function up()
{
Schema::rename('old_table_name', 'new_table_name');
}
然后在down方法中,如果您想撤销之前所做的更改,应该使用以下内容:
public function down()
{
Schema::rename('new_table_name', 'old_table_name');
}
protected $table = 'tablename';
- Mr U.protected $table = 'tablename';
这行代码? - pasindu