迁移文件保存于 Laravel项目根目录 > database > migrations
参考文档:[ Laravel 5.6 文档 ] 数据库操作 —— 迁移
创建迁移文件
要创建迁移文件,可以使用 artisan 命令提供的 make:migration 方法
- 迁移文件不需要分目录管理, 直接书写名称即可
- 会自动生成
创建时间 + 文件名的迁移文件名, 避免同名情况``php // 会在database/migrations目录中创建迁移文件2018_11_06_141425_create_paper_table.php` php artisan make:migration CreatePaperTable
// 创建成功反馈参考信息 Created Migration: 2018_11_06_141425_create_paper_table
创建的迁移文件代码如下:```php<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreatePaperTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('paper', function (Blueprint $table) {$table->increments('id');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('paper');}}
up()方法用于新增表,列或者索引到数据库down方法就是up方法的逆操作
运行迁移
要运行应用中所有未执行的迁移,可以使用 artisan 命令提供的 migrate 方法
迁移文件的 up 方法会执行,创建数据表
php artisan migrate
// 反馈信息参考如下:
Migrating: 2018_11_06_141425_create_paper_table
Migrated: 2018_11_06_141425_create_paper_table
首次执行迁移时,要先执行 install 生成迁移记录表 (新版本中可忽略该步)
php artisan migrate:install
回滚迁移
要回滚最新的一次迁移”操作“,可以使用 artisan 命令提供的 rollback 方法
迁移文件的 down() 方法执行,回滚操作, 删除数据表**
注意:回滚操作将会影响最后一批运行的迁移,可能包含多个迁移文件 回滚操作只删除迁移表中的记录和对应的数据表, 不会删除迁移文件
php artisan migrate:rollback
// 反馈信息参考如下:
Rolling back: 2018_11_06_141425_create_paper_table
Rolled back: 2018_11_06_141425_create_paper_table
Schema类
Schema是用于操作数据表的门面,调用其具体的方法之后就可以创建数据表与删除数据表。
$table->列类型方法(字段名,[长度|值范围]) -> 列修饰方法([修饰的值]);
示例代码
Schema::create('paper', function (Blueprint $table) {
// $table->列类型方法(字段名,[长度|值范围]) -> 列修饰方法([修饰的值]);
// 自增的主键id
$table->increments('id');
// 试卷名称, varchar(100), 不为空, 唯一
$table->string('paper_name', 100) -> notNull() -> unique();
// 试卷总分, 整型数字, tinyint, 默认值为100
$table->tinyInteger('total_score') -> default(100);
// 考试开始时间(时间缀), Integer类型, 允许为null
$table->integer('start_time') -> nullable();
// 考试时间, 单位分钟, tinyint
$table->tinyInteger('duration');
// 试卷是否启用的状态, tinyint, 1表示启用, 2表示禁用, 默认为1
$table->tinyInteger('status') -> default(1) ;
});
