MySQL error when creating foreign key with Laravel migration

早过忘川 提交于 2019-12-07 05:42:06

问题


I have a Laravel application set up and I'm using Sentry 2 for user authentication. I have a model called 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.

The migration that I've written is the following:

public function up()
{
    Schema::table('posts', function(Blueprint $table)
    {
        $table->integer('user_id')->after('id')->nullable();
        $table->foreign('user_id')->references('id')->on('users');
    });
}

After running it with php artisan migrate, I get a MySQL error in the command prompt:

[Illuminate\Database\QueryException]
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))

At first I thought this error occurred because the primary key column in users is defined differently than my foreign key column user_id, however they're both defined as int(10).

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.


回答1:


The foreign key should already be in database, therefore I suggest to take two steps. Also I suggest to make the column 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');
    });
}


来源:https://stackoverflow.com/questions/22122497/mysql-error-when-creating-foreign-key-with-laravel-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!