php - 无法在 Laravel 迁移中创建外键

标签 php mysql laravel

我正在开发一个使用 laravel 5.8 的项目。这里我想创建一个外键。我尝试了很多时间,但每次我都会收到有关迁移时间的错误消息。有三张表,一张是贸易表,这是主要表,学生、安置表是次要表。我想在这两个辅助表 trade_id 上创建一个外键作为键的名称。

这是交易表(主表)。

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

 class CreateTradesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('trades', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('trade', 32)->nullable();
        $table->string('unit', 32)->nullable();
        $table->string('class_room', 32)->nullable();
        $table->string('total_class_room', 32)->nullable();
        $table->string('workshop', 32)->nullable();
        $table->string('total_workshops', 32)->nullable();
        $table->string('remarks', 32)->nullable();
        $table->timestamps();
        $table->softDeletes();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('trades');
}
}

这是学生表(辅助表)。

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name', 32)->nullable();
            $table->string('father_name', 32)->nullable();
            $table->string('uid', 12)->nullable();
            $table->date('dob');
            $table->string('sex', 6)->nullable();
            $table->string('status', 16)->nullable();
            $table->integer('trade_id')->unsigned()->nullable();
            $table->foreign('trade_id')->references('id')->on('trades')->onDelete('cascade');            
            $table->string('shift', 32)->nullable();
            $table->string('session', 32)->nullable();
            $table->timestamps();
            $table->softDeletes();
        });


    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

这是展示位置表(辅助表)。

<?php

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

class CreatePlacementsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('placements', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('roll_no', 32)->nullable();
            $table->string('name', 32)->nullable();
            $table->integer('trade_id')->unsigned()->nullable();  
            $table->foreign('trade_id')->references('id')->on('trades')->onDelete('cascade');                      
            $table->year('year_of_passing');
            $table->string('organization_name', 32)->nullable();
            $table->float('salary_on_joining', 8,2);
            $table->timestamps();
            $table->softDeletes();
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('placements');
    }
}

在迁移时出现错误。

$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2019_05_22_132427_create_notices_table
Migrated:  2019_05_22_132427_create_notices_table
Migrating: 2019_05_22_132600_create_students_table

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `students` add co
nstraint `students_trade_id_foreign` foreign key (`trade_id`) references `trades` (`id`) on delete cascade)

  at C:\laragon\www\projects\UIIT-admin\uiti_admin\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      C:\laragon\www\projects\UIIT-admin\uiti_admin\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\laragon\www\projects\UIIT-admin\uiti_admin\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

最佳答案

您已将外键定义为整数类型,但 trades 表中的主键为 bigInteger 类型

试试这个

 $table->bigInteger('trade_id')->unsigned()->nullable();
 $table->foreign('trade_id')->references('id')->on('trades')->onDelete('cascade');  

关于php - 无法在 Laravel 迁移中创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56269150/

相关文章:

java - 如何在服务器上存储图像,以便可以将带有 id 的图像路径作为 map 存储在属性文件中,以便我们可以根据 id 获取图像

laravel - 在SSH Laravel 5.2中运行工匠代码

php - 变量在 whereExist 函数内未定义 - laravel

PHP fopen 找不到现有文件

javascript - CryptoJS 和 PHP SHA256

PHP exec 启动带参数的 cmd 窗口

mysql - 从 MYSQL 将数据填充到 elasticsearch 的良好实践

mysql - 我可以从任何IP地址远程访问mysql数据库吗???

java - Android apk 无法使用 PHP 检索超过 3g 的数据,在 wifi 上工作正常

mysql - 将复杂的 whereIn 与 Laravel 的查询生成器一起使用