【发布时间】:2020-01-14 01:41:12
【问题描述】:
嘿,我目前正在进行 Laravel 6 数据库迁移,但是当我执行 php artisan migrate:fresh 时,以下错误跳到我身上:
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:更改表category_post 添加约束category_post_category_id_foreign 外键(category_id)在删除级联时引用id(categories)更新级联)
我检查了以下内容:
- 错别字
- 引用顺序错误
- 自 Laravel 5.8 起从增量更改为大增量
- 类型错误
这是我的迁移代码,希望您能看到我犯的错误,因为我找不到它。
// Table for storing Blog Posts
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->string('read_time');
$table->string('summary');
$table->string('body');
/*$table->timestamps('created_at');
$table->timestamps('updated_at');*/
$table->timestamps();
});
// Table for storing categories
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('description');
$table->timestamps();
});
// Table for association of Categories with Blog Posts
Schema::create('category_post', function (Blueprint $table) {
$table->bigInteger('category_id');
$table->bigInteger('post_id');
$table->foreign('category_id')->references('id')->on('categories')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['post_id', 'category_id']);
});
// Table for association of Users with Blog Posts
Schema::create('user_post', function (Blueprint $table) {
$table->bigInteger('user_id');
$table->bigInteger('post_id');
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'post_id']);
});
毕竟目标是将类别和用户与帖子相关联,以便我可以在帖子上添加标签和用户。
提前感谢您的帮助和好意,我是 Laravel 的新手,但我对 PHP 有很好的了解,所以如果您能解释一下我做错了什么,那就太好了:)
【问题讨论】: