Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Laravel PDOException General error referencing column and referenced column in a foreign key constraint are incompatible

I am currently doing migrations in Laravel via the Terminal, and have these two errors when attempting to use php artisan migrate; I will print errors below:

Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 3780 Referencing column 'room_id' and referenced column 'id' in foreign key constraint 'contacts_room_id_foreign' are incompatible.")
      /Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

Based on the code contained within the Exception Trace, the issue seems to be within the code below:

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

class CreateContactsTable extends Migration
{
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user1_id');
            $table->unsignedInteger('user2_id');
            $table->integer('room_id')->unique();
            $table->timestamps();
            $table->foreign('room_id')->references('id')->on('rooms');
            $table->foreign('user1_id')->references('id')->on('users');
            $table->foreign('user2_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

any ideas on how I can resolve?

like image 202
Chakeeel Avatar asked Jan 30 '19 00:01

Chakeeel


3 Answers

If you're on Laravel 5.8 new migration changed to big increments, so for fixining refrencing error just change integer to bigInteger, for example:

$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Will changed to:

$table->bigInteger('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
like image 68
Payam Khaninejad Avatar answered Nov 20 '22 18:11

Payam Khaninejad


Either change original migration from

bigIncrements()

to just

increments();


Or In your foreign key column do

bigInteger()

instead of

integer()

like image 5
Emeka Obianom Avatar answered Nov 20 '22 18:11

Emeka Obianom


The foreign key must be the same as the referencing id, and hence change

$table->integer('room_id')->unique();

to

$table->unsignedBigInteger('room_id')->unique();

and it does the trick.

PS: you'll get another error

SQLSTATE[42S01]: Base table or view already exists: 1050 Table...

just delete the table and run php artisan migrate

like image 4
Arun Panneerselvam Avatar answered Nov 20 '22 18:11

Arun Panneerselvam