#数据库迁移
数据库迁移
所谓迁移就像是数据库的版本控制,
这种机制允许团队简单轻松的编辑并共享应用的数据库表结构。
迁移通常和 Laravel 的 schema 构建器结对从而可以很容易地构建应用的数据库表结构。
如果你曾经频繁告知团队成员需要手动添加列到本地数据库表结构以维护本地开发环境,
那么这正是数据库迁移所致力于解决的问题。
Laravel 的 Schema 门面提供了与数据库系统无关的创建和操纵表的支持,
在 Laravel 所支持的所有数据库系统中提供一致的、优雅的、流式的 API。
##生成迁移
- 使用Artisan命令 make:migration 创建新的迁移
- 新的迁移位于database/migration
php artisan make:migration create_users_table //users相当于表名可换为member
- 通过 --table 和 --create 选项可以用于指定表名以及该迁移是否要创建一个新的数据表
php artisan make:migration create_users_table --create=users
php artisan make:migration add_votes_to_users_table --table=users
- 使用 --path 选项,提供的路径应该是相对于应用根目录的
##迁移结构
迁移类包含up、down方法
- up 用于新增表、列、索引
- down方法与up相反的操作
- 用到 Laravel 的 Schema 构建器来创建和修改表
<?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');
}
}
##运行迁移
运行应用中所有未执行的迁移
//首次执行要执行以下句子
php artisan migrate:install
//执行成功后,migrations表中多记录,执行对象表会变化
php artisan migrate
##回滚迁移
想要回滚最新的一次迁移”操作“,可以使用 rollback 命令,
注意这将会回滚最后一批运行的迁移,可能包含多个迁移文件
php artisan migrate:rollback --step=5
- reset 回滚所有的应用迁移
php artisan migrate:reset
- 回滚数据库迁移并运行migrate
php artisan migrate:refresh
//重建数据库并填充数据...
php artisan migrate:refresh --seed
//回滚重建指定步数的迁移
php artisan migrate:refresh --seed
##删除所有表&迁移
php artisan migrate:fresh
php artisan migrate:fresh -