简体   繁体   中英

Cannot add foreign key constraint, - laravel

I am having migrations issue. Table is below.

public function up()
{
    Schema::create('users_articles_likes', function (Blueprint $table) {
        // $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->integer('article_id')->unsigned();
        $table->foreign('article_id')->references('id')->on('articles');
        $table->primary(['user_id', 'article_id']);
        $table->timestamps();
    });
}

When I try to migrate it. It doesn't push the whole table. Just pushes the user_id and article_id

and this the error I am displaying in terminal.

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table users_articles_likes add constraint users_articles_likes_user_id_foreign foreign key ( user_id ) references users ( id ))

User table

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

So the problem is because of wrong data type.. In your users table you have bigIncrements which is Big Integer data type, and in the other table integer

So try this:

$table->bigInteger('user_id')->unsigned();
// or
$table->unsignedBigInteger('user_id');

make sure you check the article_id too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM