丢弃外键的问题

Jim*_*988 12 php mysql laravel artisan

我的外键与它自己的表有关.这是为了生成具有层次结构的帖子.

现在当我尝试删除数据库中的列时,它给了我这个错误:

1553 - Cannot drop index 'post_field_properties_parent_id_index': needed in a foreign key constraint
Run Code Online (Sandbox Code Playgroud)

这是代码:

public function down()
{
        Schema::table( "post_field_properties", function( $table )
        {
            $table->dropForeign('parent_id');
            $table->dropColumn('parent_id');
        } );
}
Run Code Online (Sandbox Code Playgroud)

我似乎能够做到的唯一方法是转到phpmyadmin并删除外键本身.然后放下列.

atm*_*atm 18

刚刚为我自己的项目想出了这个.删除外键时,需要连接表名和约束中的列,然后将名称后缀为"_foreign"

http://laravel.com/docs/5.1/migrations#foreign-key-constraints

public function down()
{
        Schema::table( "post_field_properties", function( $table )
        {
            $table->dropForeign('post_field_properties_parent_id_foreign');
            $table->dropColumn('parent_id');
        });
}
Run Code Online (Sandbox Code Playgroud)

  • 可选地,您可以通过将数组传递给 dropForeign 方法来指定要删除的外键的列名:`$table->dropForeign(['parent_id']);` 在删除相关内容之前删除外键非常重要柱子。 (2认同)
  • 还可以确认这在 Laravel 5.4.30 中有效。这个答案解决了我的一些大问题:)。 (2认同)

You*_*taf 5

方法如下:

1)登录到数据库并查找外键关系的名称。如果使用phpmyadmin,请转到表,单击“结构”选项卡,单击链接“关系视图”,然后等待几秒钟以加载它。搜索字段“约束名称”。在我的示例中,这是:“ contribution_copyright_id_foreign”

2)转到Laravel迁移脚本(或创建一个)。诀窍是先删除外键关系,然后删除列。

public function down()

 {

        Schema::table('contribution', function(Blueprint $table){

            $table->dropForeign('contribution_copyright_id_foreign');

            $table->dropColumn('copyright_id');

        });
Run Code Online (Sandbox Code Playgroud)

如果要删除存在外键的表,则还必须首先删除外键关系。

这里复制

希望它能帮助某人


小智 5

我正在使用 Laravel 8,事实证明dropConstrainedForeignId我们可以用它来实现这一点。因此,代替另一个答案中提供的这个:

Schema::table( "post_field_properties", function( $table )
{
    $table->dropForeign('post_field_properties_parent_id_foreign');
    $table->dropColumn('parent_id');
});
Run Code Online (Sandbox Code Playgroud)

你可以写:

Schema::table( "post_field_properties", function( $table )
{
    $table->dropConstrainedForeignId('parent_id');
});
Run Code Online (Sandbox Code Playgroud)