laravel - @Laravel 迁移:无法在 laravel 中添加外键约束
问题描述
我正在尝试在 Laravel 中创建外键,但是当我使用 artisan 迁移我的表时,我抛出了以下错误:
λ php artisan migrate
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `fees` add constraint `fee
s_fee_type_id_foreign` foreign key (`fee_type_id`) references `feetypes` (`fee_type_id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
我的迁移代码是这样的:
费用
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('fees', function (Blueprint $table) {
$table->increments('fee_id');
$table->integer('academic_id')->unsigned();
$table->integer('level_id')->unsigned();
$table->integer('fee_type_id');
$table->string('fee_heading', 100)->nullable();
$table->float('amount', 8, 2);
$table->foreign('academic_id')->references('academic_id')->on('academics');
$table->foreign('level_id')->references('level_id')->on('levels');
$table->foreign('fee_type_id')->references('fee_type_id')->on('feetypes');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('fees');
}
}
类型
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeetypesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('feetypes', function (Blueprint $table) {
$table->unsignedinteger('fee_type_id');
$table->string('fee_type', 100);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('feetypes');
}
}
关于我做错了什么的任何想法,我现在想得到这个,因为我需要创建很多表,例如用户、学生、Leves 等。理想情况下,我想创建包含这个的表带有外键的数据,即费用和费用类型。
希望有人可以帮助我开始。
解决方案
检查所有数据类型是否与引用的数据类型匹配。
public function up()
{
Schema::create('fees', function (Blueprint $table) {
$table->increments('fee_id');
$table->unsignedInteger('academic_id');
$table->unsignedInteger('level_id');
$table->unsignedInteger('fee_type_id');
$table->string('fee_heading', 100)->nullable();
$table->float('amount', 8, 2);
$table->foreign('academic_id')->references('academic_id')->on('academics');
$table->foreign('level_id')->references('level_id')->on('levels');
$table->foreign('fee_type_id')->references('fee_type_id')->on('feetypes');
});
}
检查levels 中的level_id、academics 中的academic_id、feetypes 中的fee_type_id 也是unsignedInteger或autoincrement并将您的表格创建脚本更改为以上一个。