如何解决Laravel外键约束格式不正确errno 150
有人可以告诉我为什么我得到的外键格式不正确吗?
这是代码的一部分:
public function up()
{
Schema::create('posts',function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('title');
$table->text('content');
$table->string('featured');
$table->string('slug');
$table->foreignId('category_id')->constrained()->onDelete('cascade');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
这是类别表:
public function up()
{
Schema::create('categories',function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
注意
仅针对类别,不会删除“ user_id”外键的错误。
解决此问题
只需更改数据库/迁移的日期-例如,如果希望在发布表进行此更改之前创建类别,则进行迁移:
2020_08_06_172006_create_posts_table.php 2020_08_09_172006_create_categories_table.php
从迁移类别的更改日期 2020_08_09 ,例如 2020_ 07 _09
解决方法
我猜您的表posts
是在categories
之前创建的
因此,不能将posts.category_id
约束到categories.id
表。
为了解决该问题,您应该在创建表categories
之前创建表posts
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。