【发布时间】:2020-04-13 17:20:22
【问题描述】:
我有 2 个表,用户和朋友请求,我想创建外键,但出现以下错误。
Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1005 无法创建表
larasocial.#sql-1710_1f5(errno: 150 "外键约束格式不正确") (SQL: alter table @987654323 @添加约束friend_requests_sender_id_foreign外键(sender_id)引用users(id)在更新级联上删除级联)
用户迁移文件
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name", 255);
$table->string("surname", 255);
$table->string("email", 255);
$table->string("password", 255);
$table->date("birthday");
$table->string("gender", 255);
$table->string("photo", 255);
$table->integer("recover_code")->default(0);
$table->boolean("confirmed")->default(false);
$table->dateTime("last_visit");
$table->date("created_at");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
friend_requests 迁移文件
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFriendRequestsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('friend_requests', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer("sender_id");
$table->integer("accepter_id");
$table->foreign("sender_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
$table->foreign("accepter_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('friend_requests');
}
}
我已经尝试过其他类似问题的方法,但它们并没有解决我的问题。
【问题讨论】:
-
使用相同的数据类型。您的 users.id 是大整数,而您的 friends_requests.sender_id 使用整数。
-
@EliasSoares 谢谢你的回答。问题解决了。