Laravel Migration更改表名

HKu*_*mar 38 laravel laravel-5

我想在Laravel中更改我的两个表名,因此我必须手动更改表名,或者可以通过迁移实现.

Gaz*_*dge 88

你可以这样做:

Schema::rename($currentTableName, $newTableName);
Run Code Online (Sandbox Code Playgroud)

要删除现有表,可以使用drop或dropIfExists方法:

Schema::drop('users');

Schema::dropIfExists('users');
Run Code Online (Sandbox Code Playgroud)

只需将其添加到迁移中即可.

  • 您可以使用此行告诉您的模型使用不同的表,而不是重命名所有类:`protected $table = 'tablename';` (3认同)
  • 这还会重命名/更改控制器/模型吗? (2认同)
  • > 这也会重命名/更改控制器/模型吗?不。 (2认同)

Yev*_*yev 46

您可以像这样重命名表

Schema::rename('old_table', 'new_table');
Run Code Online (Sandbox Code Playgroud)

如果您有foreign keys,indexes和,请小心unique-s

重命名后您将无法删除它们,例如 thiat

Schema::table('new_table', function (Blueprint $table) {
   $table->dropForeign(['transaction_id']);
 });
Run Code Online (Sandbox Code Playgroud)

因为它们将具有旧名称并且这些名称中包含表名称。

因此,我建议先删除foreign keys和其他内容

 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');
 });
Run Code Online (Sandbox Code Playgroud)

  • 外键+1。我认为这同样适用于索引,因为它们也由 Laravel 自动命名(如果您不指定名称)。 (4认同)

小智 11

首先,使用 CLI 命令创建迁移:

php artisan make:migration rename_table
Run Code Online (Sandbox Code Playgroud)

现在,在新迁移类的 up 方法中,使用 rename 方法更改表名:

Schema::rename('old_table_name', 'new_table_name');
Run Code Online (Sandbox Code Playgroud)

接下来,执行迁移命令:

php artisan migrate
Run Code Online (Sandbox Code Playgroud)


Nik*_* K. 9

要重命名现有数据库表,请使用重命名方法:

Schema::rename($from, $to);
Run Code Online (Sandbox Code Playgroud)

要删除现有表,可以使用drop或dropIfExists方法:

Schema::drop('users');

Schema::dropIfExists('users');
Run Code Online (Sandbox Code Playgroud)


小智 8

首先,在终端中运行此命令以创建一个迁移文件来重命名表:

php artisan make:migration rename_old_name_to_new_name_table
Run Code Online (Sandbox Code Playgroud)

然后在 up 方法中,你应该有这样的:

public function up()
{
    Schema::rename('old_table_name', 'new_table_name');
}
Run Code Online (Sandbox Code Playgroud)

然后在 down 方法中,如果您想恢复之前所做的更改,您应该使用以下内容:

public function down()
{
    Schema::rename('new_table_name', 'old_table_name');
}
Run Code Online (Sandbox Code Playgroud)