【问题标题】:What is the difference between removeColumn and dropColumn methods on Laravel Framework?Laravel 框架上的 removeColumn 和 dropColumn 方法有什么区别?
【发布时间】:2015-07-27 04:46:09
【问题描述】:

我需要从 Laravel 迁移的表中删除一列。

通常的代码是:

$table->dropColumn([ 'city', 'country' ]);

但是你必须安装Doctrine DBAL 包才能使用dropColumn() 方法。

寻找另一种解决方案,我找到了removeColumn()方法(http://laravel.com/api/5.0/Illuminate/Database/Schema/Blueprint.html#method_removeColumn):

$table->removeColumn('city'); 
$table->removeColumn('country');

但似乎不起作用。它什么都不做,没有失败,并留下完整的列。

removeColumn 和 dropColumn 方法有什么区别?

removeColumn()方法有什么用?

【问题讨论】:

    标签: database laravel database-migration


    【解决方案1】:

    removeColumn() 方法对于大多数迁移实际上是毫无用处的。它只是从蓝图中删除列,而不是从数据库中删除。所以如果你有这个迁移:

    Schema::create('foo', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    
        $table->string('foo')->nullable();
        $table->string('bar');
    
        $table->removeColumn('foo');
    });
    

    创建的表将不包含列 foo,因为它已从架构中删除。

    【讨论】:

    • 谢谢,现在我明白为什么removeColumn() 方法不适用于迁移。而这种方法的实际应用是什么?
    • 说实话我不知道。也许它可以用于动态构建模式的更复杂的场景......
    • @JuanAntonioTubío 这个问题的答案是正确的。只是好奇为什么它没有标记为已回答?
    • 感谢@OmisakinOluwatobi 的警告。很久以前的这个问题,显然,忘了标记它!
    • 没问题,很高兴您将其标记为已回答。显然,我最近能够从这个答案中受益,尽管它会增加在标记时发现问题的机会。
    猜你喜欢
    • 2018-01-09
    • 2019-06-05
    • 2022-10-13
    • 1970-01-01
    • 2017-04-26
    • 2010-10-17
    • 2011-04-15
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多