假設很久之前創(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)在需要新增一個頭像的字段,遷移后想在表中增加字段的方法有兩種:
- 重建數(shù)據(jù)庫
在原本的遷移文件中增加字段后執(zhí)行
php artisan migrate:refresh
執(zhí)行完后會回滾數(shù)據(jù)庫的所有遷移還會接著運行 migrate 命令。相當于重建,之前的數(shù)據(jù)也會沒了。
- 新加一個遷移文件
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 方法。