Stank0V01
256
11
Laravel

General error: 1215 Cannot add foreign key constraint

Posted 8 months ago by Stank0V01

Hello guys.. I have problem with migrating my table articles.

So when i type php artisan migrate it throw me that error:

Migration table created successfully.
Migrating: 2018_11_18_162528_create_articles_table

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `articles` add constraint `articles_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

  at /home/lubomir/PhpstormProjects/iplex/sourceCode/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      /home/lubomir/PhpstormProjects/iplex/sourceCode/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /home/lubomir/PhpstormProjects/iplex/sourceCode/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  Please use the argument -v to see more details.

So.. I can't migrate it.. here is my migration file:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('title');
            $table->text('content');

            $table->unsignedInteger('user_id');

            $table->boolean('shop_article');
            $table->timestamps();
        });

        Schema::table('articles',function($table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

Please help.. Thanks in advice! <3

Please sign in or create an account to participate in this conversation.