laravel - migration已經存在的表新增表字段


注意:這種方法只適合新增字段,修改和刪除是不行的。


Schema::create改為 Schema::table ,然后把其他已經存在的字段注釋掉,如下圖所示,只需要在原來基礎上添加這些你想要添加的字段:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
//          Schema::create('posts', function (Blueprint $table) {
//            $table->increments('id');
//            $table->string('title');
//            $table->text('body');
//            $table->unsignedBigInteger('auithor_id');
//            $table->foreign('author_id')->references('id')->on('users');
//            $table->timestamp('published_at')->nullable();
//            $table->timestamps();
//        });

        Schema::table('posts', function (Blueprint $table) {
//            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->unsignedBigInteger('author_id');
            $table->foreign('author_id')->references('id')->on('users');
            $table->timestamp('published_at')->nullable();
//            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}


改完之后,把migrationsb表里面的這個migrate記錄刪除掉,不然laravel會發現已經migrate過,就不會更改。

如果沒存在其他表,一開始執行 php artisan migrate 即可,貌似這句會全部執行一遍,會報錯其他表已經存在;

所以, 我需要執行這個指定的表;

首先執行 PHP artisan tinker ; 然后 (new CreatePostsTable)->up() 執行這個表的up方法即可,刷新數據表就可以看到新增的字段啦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM