如何在Laravel中放桌子?

koo*_*oko 16 laravel-5

问题是我有这个错误:

[PDOException]

SQLSTATE [42S01]:基表或视图已存在:1050表'歌曲'已存在

这是我的迁移文件:

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

我认为解决方案只是删除表然后再次运行迁移,那么如何使用命令行在Laravel 5中删除表?我正在使用MySQL.

小智 39

要删除表,可以使用Schema :: drop方法:

Schema::drop('users');

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

  • 然后,新手会在没有表面层次的了解的情况下学会不复制/粘贴/运行代码。 (3认同)

Kha*_*eal 17

要在laravel中删除表,请创建第一个迁移

步骤放下一张桌子

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

将此添加到up函数内的migrate文件中 Schema::drop('tableName');

$ php artisan migrate
Run Code Online (Sandbox Code Playgroud)


小智 9

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

Schema::drop('users');

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

如果您要删除最后一个迁移表,也可以回滚

php artisan migration:rollback
Run Code Online (Sandbox Code Playgroud)

migrate:reset命令将回滚您应用程序的所有迁移:

php artisan migrate:reset
Run Code Online (Sandbox Code Playgroud)

migrate:fresh命令将从数据库中删除所有表,然后执行migrate命令:

php artisan migrate:fresh

php artisan migrate:fresh --seed
Run Code Online (Sandbox Code Playgroud)

  • 回滚命令应该是`php artisan migrate:rollback`。 (3认同)

Ash*_*rke 7

您需要在迁移时使用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');
    }
}
Run Code Online (Sandbox Code Playgroud)


kha*_*eeb 6

对于单表的回滚,

php artisan migrate:rollback  --path=/database/migrations/22_03_18_010_create_users_table.php
Run Code Online (Sandbox Code Playgroud)

对于同时回滚和重新迁移,

php artisan migrate:refresh --path=/database/migrations/22_03_18_010_create_users_table.php
Run Code Online (Sandbox Code Playgroud)

此命令将节省您在编辑后删除并重新迁移表的时间,初学者通常会删除迁移,然后在更改后再次迁移它。