[英]Laravel 6: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
[英]SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel 5.4
我有一个Laravel迁移无法解决的问题。
这是我的用户迁移,数据名称为:2014_12_10_000000_create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_parent_id')->nullable();
$table->unsignedInteger('company_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
这是公司表迁移,文件名是2018_06_01_080858_create_company_table.php
Schema::create('company', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
....
$table->timestamps();
});
相反,这是设置外键的迁移,文件名是:2018_11_13_111338_alter_foreign_keys.php
Schema::table('users', function($table) {
$table->foreign('user_parent_id')->references('id')->on('users');
$table->foreign('company_id')->references('id')->on('company');
});
当我尝试运行php artisan:migrate时,我总是会遇到此错误:
In Connection.php line 647:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `company` (`id`))
In PDOStatement.php line 144:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
In PDOStatement.php line 142:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
最后,进行迁移,命名为2018_11_13_111338_alter_foreign_keys.php,我为数据库中的所有其他表依次添加了所有其他外键。
任何建议都是值得欢迎的,谢谢。
这是alterForeignTable类的代码:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterForeignTable2 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function($table) {
$table->foreign('user_parent_id')->references('id')->on('users');
$table->foreign('company_id')->references('id')->on('company');
});
Schema::table('otherstable', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
}
您有两个模型,并添加了两个外部ID。 这是许多工作。 您只需要添加带有company_id和user_id的数据透视表即可
https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
首先,您必须将user_id字段设为索引:
$table->index('user_id');
之后,您可以创建一个对级联操作的外键:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
如果要通过新的迁移来做到这一点,则必须首先删除索引和外键,然后从头开始做所有事情。
在down()函数中,您必须执行此操作,然后在up()中,执行我上面写的内容:
$table->dropForeign('user_parent_id');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
试试这个,希望它能起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.