【发布时间】:2017-05-06 21:13:33
【问题描述】:
我是 laravel 的初学者。我在 laravel 中添加外键时遇到问题。我试过了,但我找不到错误。
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table laravel_home1
#sql-4b8_2a (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table `posts` add constraint
`posts_comment_id_foreign` foreign key (`comment_id`) references
`comments` (`id`))
发布表迁移代码
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('comment_id')->unsigned();
});
Schema::table('posts', function ($table) {
$table->foreign('comment_id')
->references('id')
->on('comments');
});
}
cmets表迁移代码
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('comment');
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
【问题讨论】:
-
您是否已迁移您的 cmets 表?
-
如果
comments表在posts之前创建,请同时分享comments表迁移。 -
看起来您是先创建表格帖子,而 cmets 表格不存在。
-
还要检查字段是否相同。
标签: laravel