【发布时间】:2018-08-01 22:27:52
【问题描述】:
美好的一天,我是 laravel 的新手,我正在执行迁移回滚,并且已成功完成
回滚:2018_02_22_172102_adding_fk_constrains_products_to_product_types_and_service_sub_types_table
但是当我尝试重新迁移时,我在下面遇到了这个错误。顺便说一句,我不想删除该列,因为它已经存在并且我不想丢失该列中的现有数据。我只想在这些表之间添加约束
[照亮\数据库\查询异常] SQLSTATE[23000]:违反完整性约束:1022 无法写入;表'#sql-2fc8_17c'中的重复键(SQL:更改表
products添加约束products_product_type_id_foreign更新级联时外键 (product_type_id) 引用product_types(id)[PDO异常] SQLSTATE[23000]:违反完整性约束:1022 无法写入;表'#sql-2fc8_17c'中的重复键
Table Non_unique Key_name Seq_in_index Column_name
-------- ---------- ---------------------------------- ------------ -------------------
products 0 PRIMARY 1 id
products 1 products_product_type_id_index 1 product_type_id
products 1 products_service_sub_type_id_index 1 service_sub_type_id
这是我的迁移代码
public function up()
{
Schema::table('products',function (Blueprint $table){
$table->integer('product_type_id')->unsigned()->index()->change();
$table->foreign('product_type_id')->references('id')->on('product_types')->onUpdate('cascade');
$table->integer('service_sub_type_id')->nullable()->unsigned()->index()->change();
$table->foreign('service_sub_type_id')->references('id')->on('service_sub_types')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function(Blueprint $table){
$table->dropForeign(['product_type_id']);
$table->dropForeign(['service_sub_type_id']);
});
}
【问题讨论】:
-
您可能需要检查您的 MySQL 数据库以查看外键是否确实存在,否则您可以尝试使用 Schema::disableForeignKeyConstraints();
-
Schema::disableForeignKeyConstraints();我在 down() 方法中添加了这段代码,但错误仍然存在。
-
目前您的数据库中是否确实存在该键/列?
-
是的。它存在于我的数据库中。我在更新后的问题 SHOW INDEXES FROM
products中添加了这个查询的结果; -
你看到的问题是键名实际上是'products_product_type_id_index',删除外键的laravel命名约定是使用_foreign后缀,所以在你的情况下它应该是product_type_id_foreign
标签: migration laravel-5.2