laravel 5 数据库迁移
迁移就像是数据库的版本控制
创建一个完整的数据库表流程如下
1. 生成迁移
使用 Artisan 命令 make:migration
就可以创建一个新的迁移:下面是生成了cg_website、cg_account,cg_account_website 三个表的迁移。
其格式为:
php artisan make:migration create_表名_table
yshuqdeMacBook-Pro:YaoliPay yshuq$ php artisan make:migration create_cg_website_table
Created Migration: 2022_03_08_080846_create_cg_website_table
yshuqdeMacBook-Pro:YaoliPay yshuq$ php artisan make:migration create_cg_account_table
Created Migration: 2022_03_08_080909_create_cg_account_table
yshuqdeMacBook-Pro:YaoliPay yshuq$ php artisan make:migration create_cg_account_website_table
Created Migration: 2022_03_08_080939_create_cg_account_website_table
新的迁移位于 database/migrations
目录下,每个迁移文件名都包含时间戳从而允许 Laravel 判断其顺序。
又例如我要创建users表,格式如下
php artisan make:migration create_user_table
Created Migration: 2022_05_18_032548_create_user_table
2. 迁移结构
迁移类包含了两个方法:up
和 down
。up
方法用于新增表,列或者索引到数据库,而 down
方法就是 up
方法的逆操作,和 up
里的操作相反。
在这两个方法中你都要用到 Laravel 的 Schema 构建器来创建和修改表,
创建迁移结构之后默认代码如下:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user');
}
}
3. 运行迁移
要运行应用中所有未执行的迁移,可以使用 Artisan 命令提供的 migrate
方法:
php artisan migrate
php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (44.83ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (47.47ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (28.73ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated: 2019_12_14_000001_create_personal_access_tokens_table (40.35ms)
Migrating: 2022_05_18_032548_create_user_table
Migrated: 2022_05_18_032548_create_user_table (13.08ms)
默认迁移了所有未迁移的。
迁移完成之后,如果再去执行迁移命令:php artisan migrate,则会显示Nothing to migrate.
php artisan migrate
Nothing to migrate.
在生产环境中强制运行迁移
有些迁移操作是毁灭性的,这意味着它们可能造成数据的丢失,为了避免在生产环境数据库中运行这些命令,你将会在运行这些命令之前被提示并确认。想要强制运行这些命令而不被提示,可以使用 --force
标记:
php artisan migrate --force
3.添加数据表列字段
打开生成的迁移文件。在up方法里面添加需要的字段信息
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cg_account_website', function (Blueprint $table) {
$table->increments('id');
$table->integer('pay_id');
$table->integer('account_id');
$table->integer('ui_id');
$table->timestamps();
});
}
再执行下面命令:
php artisan migrate
这个时候去数据库查看,数据表字段已经添加。