【问题标题】:Laravel migration drop column with primary key (error)带有主键的 Laravel 迁移删除列(错误)
【发布时间】:2020-05-07 13:58:23
【问题描述】:

我已经检查了其他主题,但没有适合我的解决方案。我最后一次尝试:

public function up()
{
    if(Schema::hasColumn('orders_products_variations','id')) {
        Schema::table('orders_products_variations',function (Blueprint $table) {
            $table->unsignedInteger('id')->change();
            $table->dropPrimary();
            $table->dropColumn('id');
        });
    }
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('clients', function (Blueprint $table) {
        $table->string('id');
    });
}

错误信息是:

SQLSTATE[42000]:语法错误或访问冲突:1075 表定义不正确;只能有一个自动列,并且必须定义为一个键(SQL:alter table orders_products_variations drop primary key)

有什么想法吗?

【问题讨论】:

  • 听起来id被定义为自增,所以它必须是主键。您应该能够只删除 id 列而无需任何其他箍。
  • 我已经尝试只删除 id 列,但也没有用
  • 您可能需要将其拆分为两个 Schema::table 调用。第一个将删除主键,而第二个将删除整个列。
  • 谢谢,但我也试过了
  • 您尝试删除哪一列?

标签: php sql laravel


【解决方案1】:

一个迁移类包含两个方法:向上和向下。 up方法是 用于向数据库添加新表、列或索引,同时 down 方法应该反转 up 执行的操作 方法。

删除列

要删除一列,请使用模式构建器内部向下方法中的dropColumn

if (Schema::hasColumn('table_name', 'column_name')) {
    Schema::table('table_name', function (Blueprint $table) {
       $table->dropColumn('column_name');
    });
}

添加/删除列

PS 当你必须向 Laravel 中的现有表添加新列时,你必须 创建新的迁移。

php artisan make:migration add_column_to_table

【讨论】:

  • 让我们在聊天chat.stackoverflow.com/rooms/206361/…继续这个讨论
  • 这是完全错误的。 up() 不仅用于添加,down() 不仅用于删除。 OP的问题就是一个例子。
  • 嗯,这很有趣:D 但是我仍然认为这是完全错误的,OP 的问题就是一个很好的例子,我也一直这样做。架构发生变化,有时您需要删除列 - 除了迁移,您将如何做?
  • 我在删除列之前从未使用过 up() 方法。但是,由于在运行 php artisan migrate:rollback 时会调用 down() 方法,所以我用它来删除列、表...
猜你喜欢
  • 2016-11-15
  • 2021-03-20
  • 2018-01-30
  • 2016-07-02
  • 2019-01-22
  • 2019-01-31
  • 2014-09-27
  • 1970-01-01
  • 2013-06-11
相关资源
最近更新 更多