关于laravel:laravel数据库迁移

3次阅读

共计 5925 个字符,预计需要花费 15 分钟才能阅读完成。

一:创立迁徙

在 laravel 中应用 make:migration 命令来创立迁徙

php artisan make:migration create_user_table

执行下面的命令后这时候会在 database/migrations 目录下生成对应的迁徙文件,每个迁徙的文件名都蕴含一个工夫戳来让 Laravel 确认迁徙的程序

二:迁徙构造

一个迁徙类蕴含两个办法:up 和 down。up 办法是用于新增数据库的数据表、字段或者索引的,而 down 办法应该与 up 办法的执行操作相同。

1:up 办法

public function up()
{Schema::create('user', 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();});
}

2:down 办法

public function down()
{Schema::dropIfExists('user');
}

三:运行迁徙

php artisan migrate

大多数迁徙操作都是破坏性的,这意味着兴许会失落数据。为了避免有人在生产环境数据中运行这些命令,在执行这些命令之前将提醒你进行确认。如果要强制迁徙命令在没有提醒的状况下运行,请应用 –force 参数

php artisan migrate --force

四:迁徙回滚

php artisan migrate:rollback

通过向 rollback 命令加上 step 参数,能够回滚指定数量的迁徙

php artisan migrate:rollback --step=5

migrate:reset 命令将会滚回你应用程序所有的迁徙:

php artisan migrate:reset

五:回滚后迁徙

migrate:refresh 命令将会在回滚你所有的迁徙后执行 migrate 命令。这个命令能够高效的从新创立你的整个数据库:

php artisan migrate:refresh

// 刷新数据库并执行数据库填充
php artisan migrate:refresh --seed

六:可用字段类型

在 laravel 的数据库迁徙中,反对的字段类型有:

命令 形容
$table->bigIncrements(‘id’); 递增 ID(主键),相当于「UNSIGNED BIG INTEGER」
$table->bigInteger(‘votes’); 相当于 BIGINT
$table->binary(‘data’); 相当于 BLOB
$table->boolean(‘confirmed’); 相当于 BOOLEAN
$table->char(‘name’, 100); 相当于带有长度的 CHAR
$table->date(‘created_at’); 相当于 DATE
$table->dateTime(‘created_at’); 相当于 DATETIME
$table->dateTimeTz(‘created_at’); 相当于带时区 DATETIME
$table->decimal(‘amount’, 8, 2); 相当于带有精度与基数 DECIMAL
$table->double(‘amount’, 8, 2); 相当于带有精度与基数 DOUBLE
$table->enum(‘level’, [‘easy’, ‘hard’]); 相当于 ENUM
$table->float(‘amount’, 8, 2); 相当于带有精度与基数 FLOAT
$table->geometry(‘positions’); 相当于 GEOMETRY
$table->geometryCollection(‘positions’); 相当于 GEOMETRYCOLLECTION
$table->increments(‘id’); 递增的 ID (主键),相当于「UNSIGNED INTEGER」
$table->integer(‘votes’); 相当于 INTEGER
$table->ipAddress(‘visitor’); 相当于 IP 地址
$table->json(‘options’); 相当于 JSON
$table->jsonb(‘options’); 相当于 JSONB
$table->lineString(‘positions’); 相当于 LINESTRING
$table->longText(‘description’); 相当于 LONGTEXT
$table->macAddress(‘device’); 相当于 MAC 地址
$table->mediumIncrements(‘id’); 递增 ID (主键),相当于「UNSIGNED MEDIUM INTEGER」
$table->mediumInteger(‘votes’); 相当于 MEDIUMINT
$table->mediumText(‘description’); 相当于 MEDIUMTEXT
$table->morphs(‘taggable’); 相当于退出递增的 taggable_id 与字符串 taggable_type
$table->uuidMorphs(‘taggable’); 相当于退出 taggable_id 与字符串 taggable_typeUUID 列。
$table->multiLineString(‘positions’); 相当于 MULTILINESTRING
$table->multiPoint(‘positions’); 相当于 MULTIPOINT
$table->multiPolygon(‘positions’); 相当于 MULTIPOLYGON
$table->nullableMorphs(‘taggable’); 相当于可空版本的 morphs () 字段
$table->nullableUuidMorphs(‘taggable’); 相当于可空版本的 uuidMorphs() 字段
$table->nullableTimestamps(); 相当于可空版本的 timestamps() 字段
$table->point(‘position’); 相当于 POINT
$table->polygon(‘positions’); 相当于 POLYGON
$table->rememberToken(); 相当于可空版本的 VARCHAR (100) 的 remember_token 字段
$table->set(‘flavors’, [‘strawberry’, ‘vanilla’]); 相当于 SET
$table->smallIncrements(‘id’); 递增 ID(主键),相当于「UNSIGNED SMALLINT」
$table->smallInteger(‘votes’); 相当于 SMALLINT
$table->softDeletes(); 相当于为软删除增加一个可空的 deleted_at 字段
$table->softDeletesTz(); 相当于为软删除增加一个可空的 带时区的 deleted_at 字段
$table->string(‘name’, 100); 相当于带长度的 VARCHAR
$table->text(‘description’); 相当于 TEXT
$table->time(‘sunrise’); 相当于 TIME
$table->timeTz(‘sunrise’); 相当于带时区的 TIME
$table->timestamp(‘added_on’); 相当于 TIMESTAMP
$table->timestampTz(‘added_on’); 相当于带时区的 TIMESTAMP
$table->timestamps(); 相当于可空的 created_at 和 updated_at TIMESTAMP
$table->timestampsTz(); 相当于可空且带时区的 created_at 和 updated_at TIMESTAMP
$table->tinyIncrements(‘id’); 相当于主动递增 UNSIGNED TINYINT
$table->tinyInteger(‘votes’); 相当于 TINYINT
$table->unsignedBigInteger(‘votes’); 相当于 Unsigned BIGINT
$table->unsignedDecimal(‘amount’, 8, 2); 相当于带有精度和基数的 UNSIGNED DECIMAL
$table->unsignedInteger(‘votes’); 相当于 Unsigned INT
$table->unsignedMediumInteger(‘votes’); 相当于 Unsigned MEDIUMINT
$table->unsignedSmallInteger(‘votes’); 相当于 Unsigned SMALLINT
$table->unsignedTinyInteger(‘votes’); 相当于 Unsigned TINYINT
$table->uuid(‘id’); 相当于 UUID
$table->year(‘birth_year’); 相当于 YEAR

七:字段润饰

在 laravel 的数据库迁徙中,反对的字段修饰符有:

命令 形容
->after(‘column’) 将此字段搁置在其它字段 “ 之后 ” (MySQL)
->autoIncrement() 将 INTEGER 类型的字段设置为主动递增的主键
->charset(‘utf8’) 指定一个字符集 (MySQL)
->collation(‘utf8_unicode_ci’) 指定列的排序规定 (MySQL/SQL Server)
->comment(‘my comment’) 为字段减少正文 (MySQL)
->default($value) 为字段指定 “ 默认 ” 值
->first() 将此字段搁置在数据表的 “ 首位 ” (MySQL)
->nullable($value = true) 此字段容许写入 NULL 值(默认状况下)
->storedAs($expression) 创立一个存储生成的字段 (MySQL)
->unsigned() 设置 INTEGER 类型的字段为 UNSIGNED (MySQL)
->useCurrent() 将 TIMESTAMP 类型的字段设置为应用 CURRENT_TIMESTAMP 作为默认值
->virtualAs($expression) 创立一个虚构生成的字段 (MySQL)
->generatedAs($expression) 应用指定的序列生成标识列(PostgreSQL)
->always() 定义序列值优先于标识列的输出 (PostgreSQL)
->primary(‘id’) 增加主键
->primary([‘id’, ‘parent_id’]) 增加复合键
->unique(’email’) 增加惟一索引
->index(‘state’) 增加一般索引
->spatialIndex(‘location’) 增加空间索引(不反对 SQLite)
->renameIndex(‘from’, ‘to’) 重命名索引
->dropPrimary(‘users_id_primary’) 删除主键
->dropUnique(‘users_email_unique’); 删除惟一索引
->dropIndex(‘geo_state_index’); 删除根本索引
->dropSpatialIndex(‘geo_location_spatialindex’); 删除空间索引(不反对 SQLite)

实例:

Schema::table('users', function (Blueprint $table) {$table->string('email')->nullable();});

八:批改字段

change 办法能够将现有的字段类型批改为新的类型或批改属性,例:

Schema::table('users', function (Blueprint $table) {$table->string('name', 50)->change();});

renameColumn 办法来重命名字段,依赖于 doctrine/dbal 拓展,例:

Schema::table('users', function (Blueprint $table) {$table->renameColumn('from', 'to');
});

九:删除字段

dropColumn 办法来删除字段,例:

Schema::table('users', function (Blueprint $table) {$table->dropColumn(['votes', 'avatar', 'location']);// 删除 votes,avatar,location 字段
});

十:索引长度 & Mysql / MariaDB

Laravel 默认应用 utf8mb4 编码,它反对在数据库中贮存 emojis。如果你是在版本低于 5.7.7 的 MySQL 或者版本低于 10.2.2 的 MariaDB 上创立索引,那你就须要手动配置数据库迁徙的默认字符串长度。即在 app/Providers/AppServiceProvider 中调用 Schema::defaultStringLength 办法来配置它

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{Schema::defaultStringLength(191);
}

十一:外键束缚

Laravel 还反对创立用于在数据库层中的强制援用完整性的外键束缚。例如,让咱们在 posts 表上定义一个援用 users 表的 id 字段的 user_id 字段:

Schema::table('posts', function (Blueprint $table) {$table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});

在迁徙文件中应用以下办法来开启或敞开外键束缚

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();
正文完
 0