gpt4 book ai didi

php - 如何在 laravel 5.2 迁移中删除包含外键的组合键

转载 作者:行者123 更新时间:2023-11-29 01:20:18 26 4
gpt4 key购买 nike

我有一个表(名为 j_stones),它包含 5 个字段:

id(primary key)  
j_stones_type(foreign-key)
shape
size
carat

我想让每一行都是唯一的,所以我创建了一个迁移来做到这一点:

public function up()
{
Schema::table('j_stones', function (Blueprint $table) {
$table->unique(['j_stone_types_id','shape','size','carat']);
});
}

这很好用,但是当我尝试回滚时出现以下错误:

1[照亮\数据库\查询异常]

SQLSTATE[HY000]: General error: 1553 Cannot drop index

'j_stones_j_stone_types_id_shape_size_carat_unique': needed in a foreign key constraint (SQL: alter table j_stones drop index j_stones_j_stone_types_id_shape_size_carat_unique)

[PDOException] SQLSTATE[HY000]: General error: 1553 Cannot drop index 'j_stones_j_stone_types_id_shape_size_carat_unique': needed in a foreign key constraint'

这是我的回滚代码:

    public function down()
{
Schema::table('j_stones', function (Blueprint $table) {
$table->dropUnique(['j_stone_types_id','shape','size','carat']);
});
}

我试过像这样禁用外键约束:

    public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::table('j_stones', function (Blueprint $table) {

$table->dropUnique(['j_stone_types_id','shape','size','carat']);
});
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}

还有这样的:

    public function down()
{
Schema::disableForeignKeyConstraints();
Schema::table('j_stones', function (Blueprint $table) {

$table->dropUnique(['j_stone_types_id','shape','size','carat']);
});
Schema::enableForeignKeyConstraints();
}

但是在回滚时仍然不断发生错误。
我将 MySql 与 InnoDb 一起使用。

请指教。

编辑:
我使用以下 hack 进行了回滚,但仍在寻找合适的解决方案:

    public function down()
{

Schema::table('j_stones', function (Blueprint $table) {
$table->dropForeign(['j_stone_types_id']);
$table->dropUnique(['j_stone_types_id','shape','size','carat']);
});

}

最佳答案

这里是这个 reported Laravel bug 的解决方法

public function up() {
Schema::table('contact_tags', function (Blueprint $table) {
$table->unique(['tag_id', 'contact_id'], 'tag_contact_unique'); //so that contact cannot have the same tag multiple times
});
}

public function down() {
Schema::table('contact_tags', function (Blueprint $table) {
//THE FOLLOWING 2 COMMANDS ARE THE WORKAROUND
//Although this feels weird, we first need to add the missing indexes:
$table->index('tag_id', 'tag_id_foreign');
$table->index('contact_id', 'contact_id_foreign');

//Now proceed with the main part of this "down" command to drop the unique index:
$table->dropUnique('tag_contact_unique');
});
}

关于php - 如何在 laravel 5.2 迁移中删除包含外键的组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38867425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com