问题是我有这个错误:
[PDO异常]
SQLSTATE[42S01]: 基表或视图已存在:1050 表 'songs' 已存在
这是我的迁移文件:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSongsTable extends Migration
{
public function up()
{
Schema::create('songs', function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->string('slug')->unique();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
}
我认为解决方案只是删除表然后再次运行迁移,那么如何使用命令行在 Laravel 5 中删除表?我正在使用 MySQL。
要删除表,可以使用 Schema::drop 方法:
Schema::drop('users');
// Better
Schema::dropIfExists('users');
要在 laravel 中删除表,请创建第一个迁移
丢桌子的步骤
$ php artisan make:migration drop_user_table
将此添加到您的迁移文件中 up 函数
Schema::drop('tableName');
public function up()
{
Schema::dropIfExists(table('songs'));
$table->increments('id');
...
}
然后跑
$ php artisan migrate
您可以使用 drop 或 dropIfExists 方法:
Schema::drop('users');
Schema::dropIfExists('users');
如果你想删除你最后迁移的表,你也可以回滚
php artisan migrate:rollback
migrate:reset 命令将回滚所有应用程序的迁移:
php artisan migrate:reset
migrate:fresh 命令将从数据库中删除所有表,然后执行迁移命令:
php artisan migrate:fresh
php artisan migrate:fresh --seed
你需要一个 down 方法来迁移,这样当你运行
php artisan migrate:rollback
它可以删除你的数据库。
例如
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSongsTable extends Migration
{
public function up()
{
Schema::create('songs', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->string('slug')->unique();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('songs');
}
}
删除表并再次运行迁移的简单方法。只需运行工匠命令。
php artisan migrate:fresh
注意:它将删除所有表并重新运行迁移。
或者如果你有表的种子然后运行这个命令
php artisan migrate:fresh --seed
参考:Laravel 文档
单表回滚,
php artisan migrate:rollback --path=/database/migrations/22_03_18_010_create_users_table.php
同时回滚和重新迁移,
php artisan migrate:refresh -path=\database\migrations\22_03_18_010_create_users_table.php
此命令将节省您在编辑后删除并重新迁移表的时间,通常初学者会删除迁移,然后在更改后再次迁移。
你可以运行
php artisan db:wipe
这样你将强制 laravel 删除所有表,无论外键约束如何,或者如果你在迁移时忘记了 down()
方法,就像你的情况一样。
如果您没有
down()
迁移方法,回滚将不起作用。
您也可以使用
php artisan migrate:fresh
这将强制删除所有表然后将运行所有迁移
使用以下命令在控制台中创建迁移;-
php artisan make:migration drop_table_name_table;
然后您需要将该迁移中的 up() 函数编辑为类似;-
public function up()
{
Schema::drop('table_name');
}
然后运行该迁移以完成任务。
转到迁移表并在向下函数中添加此行:
Schema::dropIfExists('tableName');
您将在迁移中将 tableName 替换为您的表名。
添加后,打开命令行并使用以下命令删除此表:
php artisan migrate:rollback --step=1 --path=database/migrations/2022_12_12_050004_create_tableName.php