Add a new column to existing table in a migration

前端 未结 12 2634
离开以前
离开以前 2020-11-28 17:09

I can\'t figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...



        
12条回答
  •  庸人自扰
    2020-11-28 17:57

    laravel 5.6 and above

    in case you want to add new column as a FOREIGN KEY to an existing table.

    Create a new migration by executing this command : make:migration

    Example :

    php artisan make:migration add_store_id_to_users_table --table=users
    

    In database/migrations folder you have new migration file, something like :

    2018_08_08_093431_add_store_id_to_users_table.php (see the comments)

    integer('store_id')->unsigned()->nullable()->after('password');
    
                // 2. Create foreign key constraints
                $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::table('users', function (Blueprint $table) {
    
                // 1. Drop foreign key constraints
                $table->dropForeign(['store_id']);
    
                // 2. Drop the column
                $table->dropColumn('store_id');
            });
        }
    }
    

    After that run the command :

    php artisan migrate
    

    In case you want to undo the last migration for any reason, run this command :

    php artisan migrate:rollback
    

    You can find more information about migrations in the docs

提交回复
热议问题