牛骨文教育服务平台(让学习变的简单)

5.5 运行迁移

使用 Artisan CLI 的 migrate:make 命令建立迁移文件:

$ php artisan migrate:make create_articles_table --create=articles

迁移文件会建立在 app/database/migrations 目录下,文件名会包含时间戳,用于在执行迁移时用来决定顺序。

app/database/migrations/2014_09_03_084339_create_articles_table.php (你的迁移文件名可能有点不一样)文件的内容如下所示:

<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create("articles", function(Blueprint $table)
        {
            $table->increments("id");
            $table->timestamps();
        });
    }

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

}

修改其中的创建代码为:

        Schema::create("articles", function(Blueprint $table)
        {
            $table->increments("id");
            $table->string("title");
            $table->text("text");
            $table->timestamps();
        });

在这个迁移中定义了一个名为 up 的方法,在运行迁移时执行。up 方法中定义的操作都是可以通过 down 方法实现可逆的,Laravel 知道如何撤销这次迁移操作。运行迁移后,会创建 articles 表,以及一个字符串字段和文本字段。同时还会创建两个时间戳字段,用来跟踪记录的创建时间和更新时间。

然后,使用 Artisan 命令运行迁移:

$ php artisan migrate

Laravel 会执行迁移操作,告诉你创建了 articles 表。

Migration table created successfully. Migrated: 2014_09_03_084339_create_articles_table