使用Laravel迁移创建外键时发生MySQL错误 [英] MySQL error when creating foreign key with Laravel migration
问题描述
我设置了Laravel应用程序,并使用 Sentry 2 进行用户验证。我有一个名为 Post
的模型,以及默认的sentry User
表。我想有一个用户有很多职位,并张贴属于一个用户。为了在我的数据库模式中体现这一点,我需要在 posts
和 users
之间创建一个外键约束。
我写的迁移如下:
public function up ()
$ table $> integer('user_id') - > after('posts',function(Blueprint $ table)
('id') - > nullable();
$ table-> foreign('user_id') - > references('id') - > on('users');
});
$ / code>
使用 起初我以为这个错误是因为主键 从Google了解到,这个错误可能是由两个列定义不同造成的,在这里似乎不是这种情况。 ñ键应该已经在数据库,所以我建议采取两个步骤。另外,我建议使列 I have a Laravel application set up and I'm using Sentry 2 for user authentication. I have a model called The migration that I've written is the following: After running it with [Illuminate\Database\QueryException] At first I thought this error occurred because the primary key column in From Google I learned that this error might be caused by the two column definitions being different, however this doesn't seem to be the case here. The foreign key should already be in database, therefore I suggest to take two steps. Also I suggest to make the column
这篇关于使用Laravel迁移创建外键时发生MySQL错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! php artisan migrate $
lockquote
[Illuminate\Database\QueryException]
$
SQLSTATE [HY000]:一般错误:
1005无法创建表'blog.dev。#sql-3bb_2d'(errno:150)(SQL:
alter table posts
add constraint posts_user_id_foreign
foreign key( user_id
)references users
(
users
中的列的定义与我的外键列 user_id
不同,但是它们都被定义为 int(10)
。
user_id
无符号:
public function up ()
$ table $> integer('user_id') - > after('posts',function(Blueprint $ table)
('id') - > nullable() - > unsigned();
});
Schema :: table('posts',function(Blueprint $ table)
{
$ table-> foreign('user_id') - > references('id ') - > on('users');
});
}
Post
along with the default sentry User
table. I would like to have a user to have many posts, and a post to belong to a user. To reflect this in my database schema, I need to create a foreign key constraint between posts
and users
.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
, I get a MySQL error in the command prompt:
SQLSTATE[HY000]: General error:
1005 Can't create table 'blog.dev.#sql-3bb_2d' (errno: 150) (SQL:
alter table posts
add constraint posts_user_id_foreign
foreign key (user_id
) references users
(id
))users
is defined differently than my foreign key column user_id
, however they're both defined as int(10)
.user_id
unsigned: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');
});
}