【问题标题】:"Foreign key constraint is incorrectly formed" on LaravelLaravel 上的“外键约束格式不正确”
【发布时间】:2021-05-26 00:06:21
【问题描述】:

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

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

("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->integer('tipo')->unsigned();来匹配相同的数据类型
  • “它不起作用”不是很准确,总是返回相同的错误?这是你的数据库引擎 InnoDB?
  • 出现同样的错误。是的,我的数据库引擎是 InnoDB

标签: php mysql laravel laravel-7 laravel-8


【解决方案1】:

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

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

$table->unsignedInteger('tipo');

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

$table->unsignedBigInteger('tipo');

【讨论】:

  • @porloscerrosΨ 你说得对,我很抱歉。 Laravel 现在默认使用 bigIncrements 创建新的迁移,因此我很困惑。更新了答案。
【解决方案2】:

请先运行

php artisan migrate:rollback

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

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

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

php artisan migrate

这会很好。我试过了。

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2019-07-25
    • 2017-10-04
    • 2018-02-19
    • 2020-09-24
    • 2019-11-02
    • 2023-03-19
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多