使用Laravel迁移创建外键时发生MySQL错误
问题描述:
我设置了Laravel应用程序,并且正在使用Sentry 2进行用户验证。我有一个名为Post
的模型以及默认的哨兵User
表。我希望有一个用户有很多帖子,和一个帖子属于一个用户。为了在我的数据库模式中反映这一点,我需要在posts
和users
之间创建一个外键约束。使用Laravel迁移创建外键时发生MySQL错误
我写的迁移如下:
public function up()
{
Schema::table('posts', function(Blueprint $table)
{
$table->integer('user_id')->after('id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
});
}
与php artisan migrate
它运行后,我得到的命令提示符下一个MySQL错误:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'blog.dev.#sql-3bb_2d' (errno: 150) (SQL: alter tableposts
add constraint posts_user_id_foreign foreign key (user_id
) referencesusers
(id
))
起初我以为这发生错误是因为users
中的主键列的定义与我的外键列user_id
不同,但它们都定义为int(10)
。
从谷歌我了解到,这个错误可能是由两个列定义不同造成的,但这似乎并不是这种情况。
答
外键应该已经在数据库中,因此我建议采取两个步骤。另外我建议使列user_id
无符号:
public function up()
{
Schema::table('posts', function(Blueprint $table)
{
$table->integer('user_id')->after('id')->nullable()->unsigned();
});
Schema::table('posts', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')->on('users');
});
}