Question

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.

Was it helpful?

Solution

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');
    });
}

OTHER TIPS

I solved with

Schema::disableForeignKeyConstraints();

before first migration and

Schema::enableForeignKeyConstraints();

in last migration

Screenshot

public function up()
{
    Schema::table('posts', function(Blueprint $table)
    {
        $table->integer('user_id')->nullable()->after('id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top