"Foreign key constraint is incorrectly formed" 在 Laravel

"Foreign key constraint is incorrectly formed" on Laravel

我正在尝试为我的数据库创建一个新的 table。

我之前创建了一个带有 PK (IdCorso) 的 table (tipo),然后是另一个带有与 tipo 关联的外键的 table(corsoscii)。
当我为 corsoscii
php artisan migrate --path='./database/migrations/2021_02_23_155544_create_corsoscii_table.php' 执行 artisan 命令时,它给我这个错误:

("SQLSTATE[HY000]: General error: 1005 Can't create table impianto_scii.corsoscii (errno: 150 "Foreign key constraint is incorrectly formed")")

这是“tipo”的设置代码

public function up()
    {
        Schema::create('tipo', function (Blueprint $table) {
            $table->increments('idCorso');
            $table->string('descrizione');
            $table->timestamps();
        });
    }

...以及“corsoscii”

  public function up()
{
    Schema::create('corsoscii', function (Blueprint $table) {
        $table->increments('idCorso');
        $table->integer('tipo');
        $table->string('nome');
        $table->integer('membriMax');
        $table->date('inizio');
        $table->date('fine');
        $table->timestamps();

    });

    Schema::table('corsoscii', function(Blueprint $table){

        $table->foreign('tipo')
            ->references('idCorso')->on('tipo')
            ->onDelete('cascade');
        
        $table->primary('idCorso');
    });
}

我是Laravel的新手,欢迎大家提出建议。

$table->integer('tipo'); 需要 完全匹配 作为外键的字段。

$table->increments('idCorso'); 生成一个 unsignedInteger,所以它应该是这样的。

$table->unsignedInteger('tipo');

如果您的迁移使用 bigIncrements,您需要使用:

$table->unsignedBigInteger('tipo');

请先运行

php artisan migrate:rollback

然后删除“corsoscii”table。然后尝试这些更改。

Schema::create('corsoscii', function (Blueprint $table) {
            $table->increments('idCorso');
            $table->integer('tipo')->unsigned();;
            $table->string('nome');
            $table->integer('membriMax');
            $table->date('inizio');
            $table->date('fine');
            $table->timestamps();

        });

        Schema::table('corsoscii', function(Blueprint $table){

            $table->foreign('tipo')
                  ->references('idCorso')->on('tipo')
                  ->onDelete('cascade');
        });

首先为 tipo 尝试 unsigned(),然后当您使用 increments() 方法时 idCorso 已经是主键。然后 运行

php artisan migrate

这会很好用。我试过了。