首页 文章

如何使用laravel迁移

提问于
浏览
3

我正在使用PHP的Laravel框架进行开发 . 我想使用迁移进行表创建操作 . 这些是我采取的步骤:

  • 我使用命令 php artisan migrate:make create_users_table 创建迁移,它创建了一个迁移文件,在其up函数中,我写下了我的模式,然后运行它并成功执行了 .

  • 之后,我再次尝试运行相同的迁移,结果显示错误“表存在” .

  • 然后我尝试使用回滚功能,但它给出了“无法回滚”的错误 .

那么,如何回滚迁移或执行迁移功能 . 此外,当我创建新的迁移和迁移文件的up函数时,我编写了用于删除由我之前的迁移创建的表的代码,并使用命令 php artisan migrate 执行,所有迁移都已执行(也是我之前的迁移)并向我显示错误, 'table already exist'(显而易见)

所以,现在我卡住了,是否有执行特殊/特定迁移的功能?我该怎么做呢?

2 回答

  • 2

    使用 artisan migrate:make 创建迁移时,应编写 updown 方法 . down 方法应该执行 up 方法的OPPOSITE .

    public function up()
    {
        Schema::create('users', function($table)
        {
            $table->increments('id');
            $table->string('username');
        });
    }
    
    public function down()
    {
        // We DROP the table because we created it in the "up" method.
        Schema::drop('users');
    }
    

    这听起来像你在 up 方法中有一些不属于那里的代码,尽管如果没有看到你的代码就很难说 . 我建议你清楚我们的 migrations 表(可能有也可能没有任何记录) . 您还需要手动删除通过迁移创建的表 . 然后你可以重新开始 .

    请记住,您也可以使用 dropIfExists 删除表,只有它存在 .

    public function down()
    {
        // Drop the table only if it exists.
        Schema::dropIfExists('users');
    }
    
  • 0

    当您在laravel中创建1个迁移时,每个迁移都包含2个方法:'up()'和'down()' .

    当你运行命令'php artisan migrate'时,up()方法将被执行 .

    当你运行命令“php artisan migrate”之前你想要恢复状态时,将会执行down()方法 .

    您可以尝试使用excuting命令:'php artisan migrate:refresh'来回滚所有迁移,并在执行命令'php artisan migrate'autal之后 .

相关问题