在 Laravel 5.4 中从迁移中删除列

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();
    });

现在我想从“列表”中删除这两列。
$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');

但有人可以编写这个新迁移,必须查找并删除这两列吗?

1
首先从数据库中删除该表,然后从迁移文件中删除这些行,并使用命令 php artisan migrate 重新迁移该表。 - Hiren Gohel
不行,我必须为此创建一个新的迁移。我不需要从列表表中删除这两列。 - Aleksandur Atanasov
要删除一列,您可以在模式生成器上使用dropColumn方法。在删除列之前,请确保将doctrine/dbal依赖项添加到您的composer.json文件中。 - Hiren Gohel
2个回答

4

Laravel Schema Builder中L5.8版本中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');

    });

  }

}

对于每个您希望删除的列,重复此操作


4
您可以这样做:
if (Schema::hasColumn('city_id', 'destination_city_id'))
{      
       $table->dropForeign('city_id');
       $table->dropForeign('destination_city_id');
       $table->dropColumn(['city_id', 'destination_city_id']);
}

在表中检查相关列是否存在总是更好的选择。

试一试,这应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接