Posted on: September 10, 2023 04:36 PM
Posted by: Renato
Views: 477
PHP Laravel PDOException General error referencing column and referenced column in a foreign key constraint are incompatible
#laravel #php #terminal
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?
Best Solution
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');
Related Solutions
Php – Illuminate\Database\QueryException SQLSTATE[42000]
Go in the App\Providers\AppServiceProvider
class and change the boot method to look like this
public function boot()
{
Schema::defaultStringLength(191);
}
Fontes
- https://itecnote.com/tecnote/php-laravel-pdoexception-general-error-referencing-column-and-referenced-column-in-a-foreign-key-constraint-are-incompatible/
.
Donate to Site
Renato
Developer