簡體   English   中英

在Laravel 5.4中從遷移中刪除列

[英]Removing columns from migration in Laravel 5.4

我使用遷移創建了一個表,如:

 Schema::create('listings', function (Blueprint $table) {
        $table->increments('id');
        $table->decimal('original_price', 10, 2);
        $table->decimal('discouted_price', 10, 2);

        $table->integer('city_id')->index()->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities');

        $table->integer('destination_city_id')->unsigned()->index();
        $table->foreign('destination_city_id')->references('id')->on('cities');

        $table->string('url');
        $table->string('titile');
        $table->text('description')->nullable();
        $table->dateTime('expires_at');
        $table->integer('clicks')->default('0');
        $table->integer('views')->default('0');
        $table->timestamps();
        $table->softDeletes();
    });

現在我想從('listing')刪除這兩個列。

$table->integer('city_id')->index()->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities');

        $table->integer('destination_city_id')->unsigned()->index();
        $table->foreign('destination_city_id')->references('id')->on('cities');

但有人可以寫這個新的遷移如何在這兩列上尋找刪除?

你可以這樣做,

if (Schema::hasColumn('city_id', 'destination_city_id'))
{      
       $table->dropForeign('city_id');
       $table->dropForeign('destination_city_id');
       $table->dropColumn(['city_id', 'destination_city_id']);
}

檢查表中是否存在relavant列總是更好。

試一試,這應該有效。

L5.8中Laravel Schema Builder中hasColumn的功能如下:

\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder::hasColumn($table,$column)
{
 return in_array(
 strtolower($column), array_map('strtolower',$this->getColumnListing($table)));

所以你應該使用你的表名作為第一個參數,就像這樣

public function up() {

 if(Schema::hasColumn('listings','city_id')) {

    Schema::table('listings',function (Blueprint $table) {

      $table->dropColumn('city_id');

    });

  }

}

重復您希望刪除的每一列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM