laravel 數(shù)據(jù)庫遷移后增加字段

假設很久之前創(chuàng)建了一張活動表

php artisan make:migration create_users_table

里面的字段如下:

.
.
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();
    });
}
.
.

現(xiàn)在需要新增一個頭像的字段,遷移后想在表中增加字段的方法有兩種:

  1. 重建數(shù)據(jù)庫
    在原本的遷移文件中增加字段后執(zhí)行
php artisan migrate:refresh

執(zhí)行完后會回滾數(shù)據(jù)庫的所有遷移還會接著運行 migrate 命令。相當于重建,之前的數(shù)據(jù)也會沒了。

  1. 新加一個遷移文件
php artisan make:migration add_avatar_into_users

然后打開遷移文件

.
.
// 運行遷移時會被調用
public function up()
{
    Schema::table('users',function (Blueprint $table) {
        $table->string('avatar')->after('name')->nullable();
    });
}

// 回滾遷移時會被調用
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('avatar');
    });
}
.
.

我們將 avatar 字段放在 name 字段后面。而修改表和創(chuàng)建表的區(qū)別就是 create 方法改成 table 方法。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容