gpt4 book ai didi

PHP Laravel PDOException 外键约束中引用列和被引用列的一般错误不兼容

转载 作者:行者123 更新时间:2023-12-03 11:21:11 25 4
gpt4 key购买 nike

我目前正在通过终端在 Laravel 中进行迁移,并且在尝试使用 php artisan migrate 时出现这两个错误;我将在下面打印错误:

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


根据异常跟踪中包含的代码,问题似乎出在以下代码中:

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


关于我如何解决的任何想法?

最佳答案

这是因为在创建 rooms 表之前设置了外键。您可以通过执行以下操作来解决此问题。


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

class CreateContactsTable extends Migration
{
public function up()
{
Schema::disableForeignKeyConstraints();
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->integer('room_id')->unsigned();
$table->integer('user1_id')->unsigned();
$table->integer('user2_id')->unsigned();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
Schema::enableForeignKeyConstraints();
}

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

关于PHP Laravel PDOException 外键约束中引用列和被引用列的一般错误不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54431456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com