首页 > 解决方案 > 将外键 unsignedBigInteger 字段更改为迁移 laravel 中的文本字段

问题描述

我有一个表foo和一个像这样的迁移(仅显示 up 方法):

public function up()
{
    Schema::table('foo', function (Blueprint $table) {
        $table->unsignedBigInteger('boo_id');
    });

    Schema::table('foo', function (Blueprint $table) {
        $table->foreign('boo_id')->references('id')->on('boos');
    });
}

所以我有一个boo_id外键boos.id。现在我想创建一个迁移,将字段更改boo_id为文本而不是外键。我怎样才能做到这一点?

标签: laravellaravel-migrations

解决方案


您首先需要删除外键和为外键创建的索引,然后更改列的数据类型。像这样的迁移会有所帮助:

public function up()
{
    Schema::table('foo', function (Blueprint $table) {
        $table->dropForeign('foo_boo_id_foreign');
        $table->dropIndex('foo_boo_id_foreign');
    });

    Schema::table('foo', function (Blueprint $table) {
        $table->text('boo_id')->change();
    });
}

请注意,它们必须在两个单独的Schema::table主体中,否则您将面临错误:Syntax error or access violation: 1170 BLOB/TEXT column 'boo_id' used in key specification without a key length (SQL: ALTER TABLE foo CHANGE boo_id boo_id TEXT DEFAULT NULL). 另请注意,传递给您的名称dropForeigndropIndex函数可能会有所不同,您应该在数据库中检查以确保,因为该命名约定不是强制性的。


推荐阅读