## 创建
通过以下命令创建迁移文件
~~~
php artisan make:migration create_xxx_table
~~~
还可以通过更简便的方式,在创建模型的时候顺带创建迁移文件
~~~
php artisan make:model xxx -m
~~~
在创建模型的时候带上-m就可以创建和模型对应的迁移文件了.
## 设置字段
~~~
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nick_name',60)->default('')->comment('昵称'); //字符串类型,长度为60
$table->string('phone')->unique(); //手机号码是唯一的
$table->string('password');
$table->string('name')->default('')->comment('姓名');
$table->tinyInteger('gender')->default(0)->comment('0是未知,1是男,2是女');
$table->string('company')->default('')->comment('公司名称');
$table->boolean('is_verify')->default(false)->comment('是否认证');//布尔类型
$table->string('api_token')->unique()->comment('api_token');
$table->dateTimeTz('expire_time')->comment('过期时间');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('users');
}
~~~
当我们运行迁移时,up方法会被调用.当我们回滚迁移时down方法会被调用.
## 进行迁移
当设置好迁移文件后使用命令进行迁移
~~~
php artisan migrate
~~~
## 运行回滚
回滚到最近一次迁移的数据库
~~~
php artisan migrate:rollback
~~~
## 对迁移文件添加字段
有时候我们需要对已经迁移过的表进行修改.laravel 也提供了方法.通过命令生成进行修改的迁移文件,在命令行后面加上--table=users指定需要添加的模型名称.
~~~
php artisan make:migration add_xxx_table --table=users
~~~
代码实现,在up方法中.
~~~
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_admin')->default(false);
});
}
~~~
通过命令完成对表的修改.
~~~
php artisan migrate
~~~