laravel实践5.laravel数据迁移

使用 数据库迁移 来管理数据库表结构,迁移就像是数据库中的版本控制,它让团队成员之间能够轻松的修改跟共享应用程序的数据库结构,而不用担心并行更新数据结构而造成冲突等问题。同时也让 Laravel 项目的部署变得很方便。不仅如此,Migration 建表要比直接手动创建表或者 .sql 文件具备额外的管理数据库的功能,如:回滚 / 重置 / 更新等。Migration 的建表方法大部分情况下能兼容 MySQL, PostgreSQL, SQLite 甚至是 Oracle 等主流数据库系统。

所有创建的迁移文件都被统一放在 database/migrations 文件夹里

实例:

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

CreateUsersTable 类继承自 Migration 基类。CreateUsersTable 有两个方法 up 和 down :

  • 当我们运行迁移时,up 方法会被调用;
  • 当我们回滚迁移时,down 方法会被调用。

创建数据表:

Schema::create('users', function (Blueprint $table) {
    ...
});

定义数据表字段:

$table->increments('id');//increments 方法创建了一个 integer 类型的自增长 id。
            $table->string('name'); //string 方法创建了一个 name 字段,用于保存用户名称。
            $table->string('email')->unique();//string 方法创建了一个 email 字段,且在最后指定该字段的值为唯一值,用于保存用户邮箱。
            $table->timestamp('email_verified_at')->nullable();//Email 验证时间,空的话意味着用户还未验证邮箱。
            $table->string('password');//string 方法创建了一个 password 字段,且在 string 方法中指定保存的值最大长度为 60,用于保存用户密码。
            $table->rememberToken();//rememberToken 方法为用户创建一个 remember_token 字段,用于保存『记住我』的相关信息。(remember_token字段和rememberToken方法为laravel users 表专用)
            $table->timestamps();//timestamps 方法创建了一个 created_at 和一个 updated_at 字段,分别用于保存用户的创建时间和更新时间。

回滚迁移:

public function down()
    {
        Schema::dropIfExists('users');
    }
原文地址:https://www.cnblogs.com/itwatcher/p/12106619.html