数据库迁移 :理解
数据库迁移
介绍
数据库迁移 ,听起来有点抽象 ,没接触过的人只听名字可能不太明白是做什么的 。先简单理解 :迁移指的是通过编程的方式创建应用程序的数据库结构( 就是用代码来对数据库中的表 、字段 、索引等对象进行增删改查 )
创建迁移
使用 Artisan 命令创建迁移 :
php artisan make:migration create_users_table
新建的迁移文件在 database/migrations/
路径下 ,文件名大概是下面这个样子 :
2014_10_12_000000_create_users_table.php
迁移文件的结构如下
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
有两个方法 up() 和 down() ,下面是对这两个方法的说明
方法 | 说明 |
---|---|
up() | 这个方法中的内容应该是对数据库中的对象( 表 、字段 、索引等 )进行增删改查等操作 |
down() | 这个方法执行的操作应该与 up() 方法相反 ,用于回滚 up() 的操作 |
表
创建表
/**
* Schema::create() 方法可以创建表
* @param $table 表的名称
* @param @callback 闭包 ,在其中对表进行各种操作
*/
Schema::create('tablename', function(Blueprint $table){
// 设置表使用的存储引擎
$table->engine = 'InnoDB';
// 设置表使用的字符编码
$table->collation = 'utf8';
// 设置表的排序规则
$table->collation = 'utf8_unicode_ci';
// 创建临时表
$table->temporary();
// 设置表的注释 ,需要插件( composer require zedisdog/laravel-schema-extend )
$this->comment = '表的注释信息';
// 设置表的注释 ,不需要插件
\DB::statement("ALTER TABLE `users` comment '表的注释信息'");
});
删除表
public function down()
{
// 删除表
Schema::drop('users');
// 如果表存在才删除表
Schema::dropIfExists('users');
}
修改表
public function up()
{
// 修改表名称
Schema::rename('old_table_name', 'new_table_name');
}
字段
增加字段
public function up()
{
Schema::table('users', function(Blueprint $table){
// 增加一个 VARCHAR(84) 类型的字段
$table->string('name', 84);
});
}
删除字段
public function down()
{
Schema::table('users', function(Blueprint $table)){
// 删除 name 字段
$table->dropColumn('name');
});
}
修改字段
public function up()
{
// 将 old_column_name 字段重命名为 new_column_name
Schema::renameColumn('old_column_name', 'new_column_name');
}
运行迁移
php artisan migrate :运行所有的迁移
运行迁移 ,不加任何选项的情况下 ,默认运行的是迁移中的 up() 方法
补充
迁移文件名称中的时间字段
下面是一个迁移文件的名称 ,其中的 2014_10_12_000000 是迁移文件的创建时间
2014_10_12_000000_create_users_table.php
迁移在执行时 ,是按照时间顺序执行的 ,up() 命令会抓取最早日期的迁移作为第一个执行 ,然后依次执行后面日期的迁移文件
创建迁移的选项
下面的命令用来创建迁移
php artisan make:migration create_users_table
有两个可用的选项
选项 | 说明 |
---|---|
--create | 创建指定名称的表进行迁移 |
# 创建一个名为 user_table 的表进行迁移
php artisan make:migration create_user_table
# 创建一个名为 abc 的表进行迁移
php artisan make:migration create_user_table --create=abc
# 相同的名称的迁移文件不能重复创建 ,这里是为了方便理解
选项 | 说明 |
---|---|
--table | 这个选项的意思我还不太明白 |
推荐文章: