![](/img/trans.png)
[英]General error: 1005 Can't create table errno: 150 “Foreign key constraint is incorrectly formed”)
[英]General error: 1005 Can't create table (errno: 150 "Foreign key constraint is incorrectly formed")
我在 Laravel 8 中有一个数据库迁移,如下所示:
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('description');
$table->text('body');
$table->string('imageUrl');
$table->string('tags');
$table->integer('viewCount')->default(0);
$table->integer('commentCount')->default(0);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
但是每当我想运行它时,我都会收到此错误:
一般错误:1005 Can't create table elearning
。 articles
(错误号:150“外键约束格式不正确”)
我不知道这里到底出了什么问题,所以如果你知道如何解决这个问题,请告诉我......
而不是使用
$table->integer('user_id')->unsigned();
利用
$table->unsignedBigInteger();
laravel 使用 20 位的 unsignedBigInteger,而 unsignedInteger 只需要 11 位
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
用户表和文章表的引擎是否相同并且都是InnoDB? MyISAM 不支持外键。 如果是,是在用户表之后创建文章表吗? 如果答案是肯定的,那么:这两个字段是否完全属于同一类型? 我认为您的用户 ID 是自动递增的,如果是,则添加未签名的外键:
$table->foreign('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade');
试试这个 Laravel 8
$table->id();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.