php Laravel的上下迁移方法是如何工作的?

deikduxw  于 2022-10-30  发布在  PHP
关注(0)|答案(4)|浏览(94)

在这段代码中,表是在up方法中创建的,而在down()方法中删除的。当我运行迁移时,表是创建的,而不是删除的。我可以通过什么方式触发down方法,以便更好地了解这两种方法的工作原理?

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}
wvyml7n5

wvyml7n51#

在您的示例中:

php artisan migrate将运行您的**up()方法。
php artisan migrate:rollback将运行您的
down()**方法。
阅读优秀的文档:https://laravel.com/docs/5.7/migrations#migration-structure

cbwuti44

cbwuti442#

您应该添加dropIfExists而不是drop
如果您只想删除特定的迁移文件,则应在命令中编写代码,如下所示:

php artisan migrate:rollback --path=\database\migrations\flights.php
nxowjjhe

nxowjjhe3#

请尝试:

public function down()
{
    Schema::dropIfExists('flights');
}
nwnhqdif

nwnhqdif4#

基本上,up()用于在数据库中创建表或修改表,而down()用于恢复这些更改。这两种方法都创建了您自己的逻辑来决定如何进行更改。
调用这些方法:向上()php artisan migrate向下()php artisan migrate:rollback

相关问题