數據庫遷移創建表
本篇文章中使用的是mysql數據庫,其他數據庫需要修改env文件和app配置,請其他地方搜索一下就會找到。
創建示例
1.創建users表:
命令行鍵入
1 php artisan make:migration create_users_table //users復數
或
1 php artisan make:migration create_users_table --create=users//--create及對應的表名 users
執行命令后,會在 /database/migrations/ 文件夾下生成對應的數據庫遷移文件,通過修改文件里的up 方法和 down方法;
- 當我們運行遷移時,
up
方法會被調用。 - 當我們回滾遷移時,
down
方法會被調用。
1 public function up() 2 { 3 Schema::create('users', function (Blueprint $table) { 4 $table->bigIncrements('id'); 5 $table->string('name')->unique(); 6 $table->string('email')->unique(); 7 $table->timestamp('email_verified_at')->nullable(); 8 $table->string('password'); 9 $table->rememberToken(); 10 $table->timestamps(); 11 }); 12 }
2.創建一個數據模型的時候 需要同時創建對應遷移文件可以加上 –m:
1 php artisan make:model Models/Moment -m
就在Models文件夾下創建了Moment數據模型 -m在 database/migrations創建了對應的數據庫遷移文件。【注:類似的還有-f【工廠類】 –c【控制器】,可以合用-cfm,-cm等】
保存后執行
1 php artisan migrate
會創建對應up方法中配置的字段的數據表。
【上面up方法中創建一個名為users的數據表,表包含id,name,email,email_verified_at,password,rememberToken[注:記住我選項被選中時生成],created_at,updated_at字段】
數據庫遷移創建表
今后若想修改完善之前的已經創建好的數據表 不能再操作之前的數據庫遷移文件。
修改 新增或刪除字段需要創建一個新的數據庫遷移文件:
操作前
請檢查你的composer.json文件中已經添加好了doctrine/dbal依賴,Doctrine DBAL庫是用來確定數據表中字段當前狀態,及用於實現目標調整的SQL查詢語句的創建工作的,安裝依賴請在控制台中執行:
1 composer require doctrine/dbal
安裝完成后,接下來:
新增字段
在控制台中執行命令:
php artisan make:migration add_要添加的字段名_to_要添加字段的表名_table --table=要添加字段的表名
migrate的文件名稱 上面那樣寫只是為了盡量規范而已,重要的是遷移文件里面的內容:
為示例向users表中添加一個post_id字段,所以我們的命令如下:
1 php artisan make:migration add_post_id_to_users_table --table=users
然后會在database/migrations創建了對應的數據庫遷移文件***_add_post_id_to_users_table.php:
1 public function up() 2 { 3 Schema::table('users', function (Blueprint $table) { 4 $table->bigInteger('post_id')->nullable()->after('email'); 5 }); 6 } 7 8 public function down() 9 { 10 Schema::table('users', function (Blueprint $table) { 11 $table->dropColumn('post_id'); 12 }); 13 }
【注意方法里已經不是Schema::create方法的調用,而是Schema::table方法的調用了。】
然后,運行
1 php artisan migrate
修改原有字段屬性
如果是修改,就調用change方法即可,比如想增加name
字段的字符串長度:
1 Schema::table('users', function (Blueprint $table) { 2 $table->string('name', 50)->change(); 3 });
比如將字段修改為可空:
1 Schema::table('users', function (Blueprint $table) { 2 $table->string('name', 50)->nullable()->change(); 3 });
1 php artisan migrate
修改字段名
1 Schema::table('users', function (Blueprint $table) { 2 $table->renameColumn('from', 'to');//from字段改名為to字段 3 });
1 php artisan migrate
刪除字段
如果目的是刪除之前已經存在的表的某些字段,新建數據庫遷移文件后,在該文件的up方法中鍵入如下代碼;
1 Schema::table('users', function (Blueprint $table) { 2 $table->dropColumn('votes');//刪除users表的votes字段 3 }); 4 5 Schema::table('users', function (Blueprint $table) { 6 $table->dropColumn(['votes', 'avatar', 'location']);//刪除users表里面的votes,avatar,location這三個字段 7 });
1 php artisan migrate