How can I rename column in laravel using migration?

前端 未结 6 646
名媛妹妹
名媛妹妹 2020-12-04 20:55

I have columns as mentioned bellow:

public function up()
{
    Schema::create(\'stnk\', function(Blueprint $table)
    {
        $table->increments(\'id\         


        
6条回答
  •  半阙折子戏
    2020-12-04 21:13

    Throwing my $0.02 in here since none of the answers worked, but did send me on the right path. What happened was that a previous foreign constraint was throwing the error. Obvious when you think about it.

    So in your new migration's up method, first drop that original constraint, rename the column, then add the constraint again with the new column name. In the down method, you do the exact opposite so that it's back to the sold setting.

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('proxy4s', function (Blueprint $table) {
            // Drop it
            $table->dropForeign(['server_id']);
    
            // Rename
            $table->renameColumn('server_id', 'linux_server_id');
    
            // Add it
            $table->foreign('linux_server_id')->references('id')->on('linux_servers');
        });
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('proxy4s', function (Blueprint $table) {
            // Drop it
            $table->dropForeign(['linux_server_id']);
    
            // Rename
            $table->renameColumn('linux_server_id', 'server_id');
    
            // Add it
            $table->foreign('server_id')->references('id')->on('linux_servers');
        });
    }
    

    Hope this saves someone some time in the future!

提交回复
热议问题