mysql执行带外键的sql文件时出现mysql ERROR 1
2019-10-23 本文已影响0人
LeeShun
ERROR 1215 (HY000): Cannot add foreign key constraint
在用laravel建表时遇到了这个错误,然后找了下找到了解决办法,记录下:
是要建两张表:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedTinyInteger('status');
$table->string('title');
$table->string('preview');
$table->longText('content');
$table->unsignedInteger('author_id')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
$table->engine = 'InnoDB';
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
出现如下提示:
微信截图_20191023204228.png
检查了数据库结构,如图
微信图片_20191023204630.png 微信图片_20191023204636.png
发现错误是users表主键使用了bigint 因为你要添加外键时,你的外键类型就是bigint,而引用的主键类型也必须是 bigint,如果你的主键设置auto_increment(那么你的字段类型实际上是unsigned_bigint)
得出结论:主键,外键类型不一致,所以无法添加外键。