@Chiang
2019-12-13T11:14:38.000000Z
字数 7367
阅读 867
Laravel
数据库迁移就像是数据库的版本控制,可以让你的团队轻松修改并共享应用程序的数据库结构。迁移通常会搭配上 Laravel 的数据库结构构造器来让你方便地构建数据库结构
- 使用 make:migration Artisan 命令 来创建迁移
- 新的迁移文件将会被放置在 database/migrations 目录中。每个迁移文件的名称都包含了一个时间戳,以便让 Laravel 确认迁移的顺序。
- --table 和 --create 选项可用来指定数据表的名称,或是该迁移被执行时会创建的新数据表。这些选项需在预生成迁移文件时填入指定的数据表
- 如果你想为生成的迁移指定一个自定义输出路径,则可以在运行 make:migration 命令时添加 --path 选项。提供的路径必须是相对于应用程序的基本路径
php artisan make:migration create_users_tablephp artisan make:migration create_users_table --create=usersphp artisan make:migration add_votes_to_users_table --table=users
一个迁移类会包含两个方法: up 和 down 。 up 方法可为数据库添加新的数据表、字段或索引,而 down 方法则是 up 方法的逆操作。
<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateFlightsTable extends Migration{/*** 运行数据库迁移** @return void*/public function up(){Schema::create('flights', function (Blueprint $table) {$table->increments('id');$table->string('name');$table->string('airline');$table->timestamps();});}/*** 回滚数据库迁移** @return void*/public function down(){Schema::drop('flights');}}
php artisan migratephp artisan migrate --force
# 若要回滚最后一次迁移,则可以使用 rollback 命令。此命令是对上一次执行的「批量」迁移回滚,其中可能包括多个迁移文件php artisan migrate:rollback# 在 rollback 命令后加上 step 参数,你可以限制回滚迁移的个数。例如,下面的命令将会回滚最后的 5 个迁移。php artisan migrate:rollback --step=5# migrate:reset 命令可以回滚应用程序中的所有迁移php artisan migrate:reset# migrate:refresh 命令不仅会回滚数据库的所有迁移还会接着运行 migrate 命令。所以此命令可以有效的重新创建整个数据库php artisan migrate:refresh# 刷新数据库结构并执行数据填充php artisan migrate:refresh --seed# 使用 refresh 命令并加上 step 参数,你也可以限制执行回滚和再迁移的个数。比如,下面的命令会回滚并再迁移最后的 5 个迁移php artisan migrate:refresh --step=5
要创建一张新的数据表,可以使用 Schema facade 的 create 方法。create 方法接收两个参数:第一个参数为数据表的名称,第二个参数为一个 闭包 ,此闭包会接收一个用于定义新数据表的 Blueprint 对象
Schema::create('users', function (Blueprint $table) {$table->increments('id');});
你可以方便地使用 hasTable 和 hasColumn 方法来检查数据表或字段是否存在
if (Schema::hasTable('users')) {//}if (Schema::hasColumn('users', 'email')) {//}
如果你想要在一个非默认的数据库连接中进行数据库结构操作,可以使用 connection 方法
Schema::connection('foo')->create('users', function (Blueprint $table) {$table->increments('id');});
你可以在数据库结构构造器上设置数据表的选项
// 指定数据表的engine(Mysql).$table->engine = 'InnoDB';// 指定数据表的默认字符集(Mysql).$table->charset = 'utf8';// 指定数据表默认的collation.$table->collation = 'utf8_unicode_ci';// 创建临时表(不支持SQL Server).$table->temporary();
// 若要重命名一张已存在的数据表,可以使用 rename 方法Schema::rename($from, $to);// 要删除已存在的数据表,可使用 drop 或 dropIfExists 方法Schema::drop('users');Schema::dropIfExists('users');
使用 Schema facade 的 table 方法可以更新已有的数据表。如同 create 方法,table 方法会接收两个参数:一个是数据表的名称,另一个则是接收 Blueprint 实例的闭包。我们可以使用它来为数据表新增字段
Schema::table('users', function (Blueprint $table) {$table->string('email');});
数据库结构构造器包含了许多字段类型,供你构建数据表时使用
$table->bigIncrements('id'); 递增 ID(主键),相当于「UNSIGNED BIG INTEGER」型态。$table->bigInteger('votes'); 相当于 BIGINT 型态。$table->binary('data'); 相当于 BLOB 型态。$table->boolean('confirmed'); 相当于 BOOLEAN 型态。$table->char('name', 4); 相当于 CHAR 型态,并带有长度。$table->date('created_at'); 相当于 DATE 型态$table->dateTime('created_at'); 相当于 DATETIME 型态。$table->dateTimeTz('created_at'); DATETIME (带时区) 形态$table->decimal('amount', 5, 2); 相当于 DECIMAL 型态,并带有精度与基数。$table->double('column', 15, 8); 相当于 DOUBLE 型态,总共有 15 位数,在小数点后面有 8 位数。$table->enum('choices', ['foo', 'bar']); 相当于 ENUM 型态。$table->float('amount', 8, 2); 相当于 FLOAT 型态,总共有 8 位数,在小数点后面有 2 位数。$table->increments('id'); 递增的 ID (主键),使用相当于「UNSIGNED INTEGER」的型态。$table->integer('votes'); 相当于 INTEGER 型态。$table->ipAddress('visitor'); 相当于 IP 地址形态。$table->json('options'); 相当于 JSON 型态。$table->jsonb('options'); 相当于 JSONB 型态。$table->longText('description'); 相当于 LONGTEXT 型态。$table->macAddress('device'); 相当于 MAC 地址形态。$table->mediumIncrements('id'); 递增 ID (主键) ,相当于「UNSIGNED MEDIUM INTEGER」型态。$table->mediumInteger('numbers'); 相当于 MEDIUMINT 型态。$table->mediumText('description'); 相当于 MEDIUMTEXT 型态。$table->morphs('taggable'); 加入整数 taggable_id 与字符串 taggable_type。$table->nullableMorphs('taggable'); 与 morphs() 字段相同,但允许为NULL。$table->nullableTimestamps(); 与 timestamps() 相同,但允许为 NULL。$table->rememberToken(); 加入 remember_token 并使用 VARCHAR(100) NULL。$table->smallIncrements('id'); 递增 ID (主键) ,相当于「UNSIGNED SMALL INTEGER」型态。$table->smallInteger('votes'); 相当于 SMALLINT 型态。$table->softDeletes(); 加入 deleted_at 字段用于软删除操作。$table->string('email'); 相当于 VARCHAR 型态。$table->string('name', 100); 相当于 VARCHAR 型态,并带有长度。$table->text('description'); 相当于 TEXT 型态。$table->time('sunrise'); 相当于 TIME 型态。$table->timeTz('sunrise'); 相当于 TIME (带时区) 形态。$table->tinyInteger('numbers'); 相当于 TINYINT 型态。$table->timestamp('added_on'); 相当于 TIMESTAMP 型态。$table->timestampTz('added_on'); 相当于 TIMESTAMP (带时区) 形态。$table->timestamps(); 加入 created_at 和 updated_at 字段,允许为NULL。$table->timestampsTz(); 加入 created_at and updated_at (带时区) 字段,并允许为NULL。$table->unsignedBigInteger('votes'); 相当于 Unsigned BIGINT 型态。$table->unsignedInteger('votes'); 相当于 Unsigned INT 型态。$table->unsignedMediumInteger('votes'); 相当于 Unsigned MEDIUMINT 型态。$table->unsignedSmallInteger('votes'); 相当于 Unsigned SMALLINT 型态。$table->unsignedTinyInteger('votes'); 相当于 Unsigned TINYINT 型态。$table->uuid('id'); 相当于 UUID 型态。
Schema::table('users', function (Blueprint $table) {$table->string('email')->nullable();});
->after('column') 将此字段放置在其它字段「之后」(仅限 MySQL)->comment('my comment') 增加注释->default($value) 为此字段指定「默认」值->first() 将此字段放置在数据表的「首位」(仅限 MySQL)->nullable() 此字段允许写入 NULL 值->storedAs($expression) 创建一个存储的生成字段 (仅限 MySQL)->unsigned() 设置 integer 字段为 UNSIGNED->virtualAs($expression) 创建一个虚拟的生成字段 (仅限 MySQL)
在修改字段之前,请务必在你的 composer.json 中增加 doctrine/dbal 依赖。Doctrine DBAL 函数库被用于判断当前字段的状态以及创建调整指定字段的 SQL 查询。
composer require doctrine/dbal
Schema::table('users', function (Blueprint $table) {$table->string('name', 50)->change();});Schema::table('users', function (Blueprint $table) {$table->string('name', 50)->nullable()->change();});
char,double,enum,mediumInteger,timestamp,tinyInteger,ipAddress,json,jsonb,macAddress,mediumIncrements,morphs,nullableMorphs,nullableTimestamps,softDeletes,timeTz,timestampTz,timestamps,timestampsTz,unsignedMediumInteger,unsignedTinyInteger,uuid
# 依赖composer require doctrine/dbal
Schema::table('users', function (Blueprint $table) {$table->renameColumn('from', 'to');});
Schema::table('users', function (Blueprint $table) {$table->dropColumn('votes');});Schema::table('users', function (Blueprint $table) {$table->dropColumn(['votes', 'avatar', 'location']);});
$table->primary('id'); 加入主键。$table->primary(['first', 'last']); 加入复合键。$table->unique('email'); 加入唯一索引。$table->unique('state', 'my_index_name'); 自定义索引名称。$table->unique(['first', 'last']); 加入复合唯一键。$table->index('state'); 加入基本索引。
Laravel 默认使用 utf8mb4 字符,包括支持在数据库存储「表情」。如果你正在运行的 MySQL release 版本低于5.7.7 或 MariaDB release 版本低于10.2.2 ,为了MySQL为它们创建索引,你可能需要手动配置迁移生成的默认字符串长度,你可以通过调用 AppServiceProvider 中的 Schema::defaultStringLength 方法来配置它
use Illuminate\Support\Facades\Schema;/*** 引导任何应用程序服务。** @return void*/public function boot(){Schema::defaultStringLength(191);}
若要移除索引,则必须指定索引的名称。Laravel 默认会自动给索引分配合理的名称。其将数据表名称、索引的字段名称及索引类型简单地连接在了一起。
$table->dropPrimary('users_id_primary'); 从「users」数据表移除主键。$table->dropUnique('users_email_unique'); 从「users」数据表移除唯一索引。$table->dropIndex('geo_state_index'); 从「geo」数据表移除基本索引。Schema::table('geo', function (Blueprint $table) {$table->dropIndex(['state']); // 移除索引 'geo_state_index'});
Schema::table('posts', function (Blueprint $table) {$table->integer('user_id')->unsigned();$table->foreign('user_id')->references('id')->on('users');});$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');$table->dropForeign('posts_user_id_foreign');$table->dropForeign(['user_id']);Schema::enableForeignKeyConstraints();Schema::disableForeignKeyConstraints();
