Laravel中如何做数据库迁移

总的来说,做一次独立数据库迁移只需要三步,分别是创建迁移文件、修改迁移文件、运行迁移

1.创建数据库迁移文件
php artisan make:migration create_articles_table
1
然后在database/migrations 目录下就会多出一个迁移文件,不过Laravel会在前面自动加上时间戳,来判断执行顺序
然后命令后面可以加上–table 或者 –create 来指定迁移文件对应的表名或者是新建一个数据表

php artisan make:migration create_articles_table --create=article
php artisan make:migration create_articles_table --table=article
1
2
2.修改迁移文件
打开新建文件我们会发现里面包含了两个方法up和down

当运行迁移时,调用up 方法
当回滚迁移时,调用down 方法

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
我们主要修改up 方法,而Laravel已经为我们生成了两个字段,我们在上面添加两个字段

public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->timestamps();
});
}
1
2
3
4
5
6
7
8
9
3.运行迁移
php artisan migrate
1
Laravel会自动寻找没有执行的迁移文件,如果你只想执行指定文件的话,可以在后面加上–path参数,指定文件名

然后我们可以连接数据库,看到新建了一张名为article的表,同时里面包含了5个字段。


如果要回滚迁移的话
1.回滚所有迁移

php artisan migrate:reset
1
2.回滚最后一次执行的迁移

php artisan migrate:rollback
1
3.重置数据库并重新运行所有迁移

php artisan migrate:refresh

posted @ 2019-05-02 14:11  yzloo  阅读(320)  评论(0编辑  收藏  举报