【问题标题】:Change foreign key unsignedBigInteger field to be text field in migration laravel将外键 unsignedBigInteger 字段更改为迁移 laravel 中的文本字段
【发布时间】:2021-06-30 15:38:21
【问题描述】:

我有一个表 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');
    });
}

所以我在boos.id 上有一个boo_id 外键。现在我想创建一个迁移,将字段boo_id 更改为文本而不是外键。我该怎么做?

【问题讨论】:

    标签: laravel laravel-migrations


    【解决方案1】:

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

    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 函数的名称对您来说可能不同,您应该在数据库中检查以确保,因为该命名约定不是强制性的。

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2017-12-21
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2023-03-10
      • 2018-06-18
      相关资源
      最近更新 更多