美工统筹SEO,为企业电子商务营销助力!
Laravel 5框架进修之数据库迁徙(Migrations)
一佰互联网站开辟设想(www.taishanly.com) 宣布日期 2020-04-28 13:45:26 阅读数: 143
database migrations 是laravel最壮大的功效之一。数据库迁徙能够或许懂得为数据库的版本节制器。
在 database/migrations 目次中包罗两个迁徙文件,一个成立用户表,一个用于用户暗码重置。
在迁徙文件中,up 体例用于建立数据表,down体例用于回滚,也便是删除数据表。
履行数据库迁徙
复制代码 代码以下:php artisan migrate#输入Migration table created successfully.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_table
查抄mysql数据库,能够或许看到发生了三张表。 migratoins 表是迁徙记实表,users 和 pasword_resets。
若是设想有题目,履行数据库回滚
复制代码 代码以下:php artisan migrate:rollback#输入Rolled back: 2014_10_12_100000_create_password_resets_tableRolled back: 2014_10_12_000000_create_users_table
再次查抄mysql数据库,就剩下 migrations 表了, users password_resets 被删除。
点窜迁徙文件,再次履行迁徙。
新建迁徙
复制代码 代码以下:php artisan make:migration create_article_table --create="articles"#输入Created Migration: 2015_03_28_050138_create_article_table
在 database/migrations 下天生了新的文件。
<?phpuse IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateArticleTable 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::drop("articles"); }}
主动增加了 id列,主动增加,timestamps() 会主动发生 created_at 和 updated_at 两个时候列。咱们增加一些字段:
public function up() { Schema::create("articles", function(Blueprint $table) { $table->increments("id"); $table->string("title"); $table->text("body"); $table->timestamp("published_at"); $table->timestamps(); }); }
履行迁徙:
复制代码 代码以下:php artisan migrate
此刻有了新的数据表了。
假定咱们须要增加一个新的字段,你能够或许回滚,而后点窜迁徙文件,再次履行迁徙,或能够或许间接新建一个迁徙文件
复制代码 代码以下:php artisan make:migration add_excerpt_to_articels_table
查抄新发生的迁徙文件
<?phpuse IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class AddExcerptToArticelsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // } /** * Reverse the migrations. * * @return void */ public function down() { // }}
只要空的 up 和 down 体例。咱们能够或许手工增加代码,或咱们让laravel为咱们天生根本代码。删除这个文件,从头天生迁徙文件,注重增加参数:
复制代码 代码以下:php artisan make:migration add_excerpt_to_articels_table --table="articles"
此刻,up 体例外面有了初始代码。
public function up() { Schema::table("articles", function(Blueprint $table) { // }); }
增加现实的数据点窜代码:
public function up() { Schema::table("articles", function(Blueprint $table) { $table->text("excerpt")->nullable(); }); } public function down() { Schema::table("articles", function(Blueprint $table) { $table->dropColumn("excerpt"); }); }
nullable() 表现字段也能够或许为空。
再次履行迁徙并查抄数据库。
若是咱们为了好玩,履行回滚
复制代码 代码以下:php artisan migrate:rollback
excerpt 列不了。
以上所述便是本文的全数内容了,但愿能够或许给大师谙练把握Laravel5框架有所赞助。