将外键 unsignedBigInteger 字段更改为迁移中的文本字段 laravel
Change foreign key unsignedBigInteger field to be text field in migration laravel
我有一个 table 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
更改为文本而不是外键。我该怎么做?
您首先需要删除外键和为外键创建的索引,然后更改列的数据类型。像这样的迁移会有所帮助:
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)
。另请注意,传递给 dropForeign
和 dropIndex
函数的名称可能与您不同,您应该在您的数据库中检查以确保这一点,因为该命名约定不是强制性的。
我有一个 table 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
更改为文本而不是外键。我该怎么做?
您首先需要删除外键和为外键创建的索引,然后更改列的数据类型。像这样的迁移会有所帮助:
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)
。另请注意,传递给 dropForeign
和 dropIndex
函数的名称可能与您不同,您应该在您的数据库中检查以确保这一点,因为该命名约定不是强制性的。