Laravel 技术笔记 (三)【Migrations 迁移】

介绍

迁移就像是资料库的版本控制器,并且让你可以轻鬆地去定义资料库的结构,包含新增资料表、修改栏位、创建索引...等等都可以透过程式码来定义,并且当进行团队协作时,你可以透过迁移很快的分享你对资料库的改动或结构给你的伙伴。


新增迁移

迁移是一系列的档案,放在 database/migrations 目录下,你可以使用 artisan 提供的指令来新增迁移,新增时你可以选填两个参数,--create={table_name} 会在新增迁移档案时预先撰写好新增「table_name」资料表的程式码,而 --table={table_name} 则会预先撰写好已经存在的「table_name」资料表的程式码:

$ php artisan make:migration create_books_table --create=books
/* 新增资料表 */<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;return new class extends Migration{    public function up()    {        Schema::create('books', function (Blueprint $table) {            $table->id();            $table->timestamps();        });    }    public function down()    {        Schema::dropIfExists('books');    }};
$ php artisan make:migration create_books_table --table=books
/* 已经存在的资料表 */<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;return new class extends Migration{    public function up()    {        Schema::table('books', function (Blueprint $table) {            //        });    }    public function down()    {        Schema::table('books', function (Blueprint $table) {            //        });    }};

定义迁移

当我们新增一个 Laravel 专案时,会发现在目录下已经有几个迁移档案存在,我们先看看 2014_10_12_000000_create_users_table.php 这个档案的内容:

<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;return new class extends Migration{    public function up()    {        Schema::create('users', function (Blueprint $table) {            $table->id();            $table->string('name');            $table->string('email')->unique();            $table->timestamp('email_verified_at')->nullable();            $table->string('password');            $table->rememberToken();            $table->timestamps();        });    }    public function down()    {        Schema::dropIfExists('users');    }};

档案中有两个已经定义好的方法 up 和 down,这两个方法都是告诉应用程式具体要对资料库做甚么样的修改,差别在于 up 是去「执行」修改,down 是「撤销」修改,上图中 up 方法里的 Schema::create() 意思是新增一张名为 users 的资料表,并且透过 $table-> 语法给予资料表栏位与指定资料的型态,至于 down 方法里的 dropIfExists() 则是检查资料库是否有 users 这个资料表,如果存在就把资料表删除。
※关于如何透过迁移操作栏位(新增栏位、修改栏位、创建索引、添加外键...等等),由于语法众多,详情请见 Laravel 官方网站


执行迁移

定义好迁移后执行以下 artisan 指令(.env 档案内关于资料库的设定务必先设定完毕否则会报错),Laravel 便会按照档案名称的时间先后检查所有迁移档案是否被执行,并将那些还没执行过的全部执行:

$ php artisan migrate

另外指令也支援许多额外选项供操作:

/* 恢复到执行全部迁移之前的初使状态 */$ php artisan migrate:reset/* 恢复到执行全部迁移档案之前的初使状态,再执行每一个迁移 */$ php artisan migrate:refresh/* 删除所有资料表(不执行 down 而是直接删除资料表),再执行每一个迁移 */$ php artisan migrate:fresh/* 只恢复到你上一次执行迁移的状态,可添加参数 --step={n},指定恢复的数量 */$ php artisan migrate:rollback --step=1/* 显示一个列出所有迁移的表格,旁边会显示 Yes 或 No 表示是否已经执行过,显示的数字则代表是第几次执行指令时执行这个迁移档案 */$ php artisan migrate:status

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章