大家好,
我试图在以前实现的Laravel 5.2迁移中删除外键:
编辑:在表中创建id(在表上使用外键之前)是:
$table->integer('agent_rights_id')->unsigned()->nullable();
外键:
Schema::table('agents', function (Blueprint $table){
$table->foreign('agent_rights_id')->references('id')->on('agent_rights');
});
我的drop是这样的:
Schema::table('agents', function (Blueprint $table){
$table->dropForeign('agents_agent_rights_id_foreign');
$table->dropColumn('agent_rights_id');
});
我发现,必须使用"真实的"索引名而不是标签——这一点我在前面的代码片段中已经想到了(作为对这个问题的引用)。
但是这给了我错误:
[IlluminateDatabaseQueryException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './{name}/agents' to './{name}/#sql2-2a6-1d8' (errno: 152) (SQL: alter table `agents` drop foreign key `agents_agent_rights_id_foreign`)
[PDOException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './{name}/agents' to './{name}/#sql2-2a6-1d8' (errno: 152)
研究这个没有真正的解决方案,只有错误的消息从MySQL…
问题:你们对此有什么看法,或者我的代码片段有什么问题吗?
@Mentenyia在创建外键约束之前使用unsigned()
是必须的。请阅读链接https://laravel3.veliovgroup.com/docs/database/schema#foreign-keys。
注意:外键中引用的字段很可能是auto自增,因此自动为无符号整数。请确保使用unsigned()作为两个字段创建外键字段必须是完全相同的类型,两个桌子上的引擎必须是设置为InnoDB,并且所引用的表必须在创建前创建使用外键的表
所以你应该像这样创建:
$table->integer('agent_rights_id')->unsigned(); // Always create column before creating Foreign key constraint otherwise this will also give error.
$table->foreign('agent_rights_id')->references('id')->on('agent_rights');
当你要删除外键时,不会出现任何问题/错误。
table-name_column-name_index-type
$table->dropForeign('agents_agent_rights_id_foreign');