LARAVEL 迁移错误 SQLSTATE[42000] "exist in table"

LARAVEL Migrate ERROR SQLSTATE[42000] "exist in table"

我在 运行 迁移 artisan 时收到错误消息

首先是我想 运行 建立关系 Many-to-Many 并向关系 many-to-many 添加 table 并且我迁移时发生的错误出现在终端。

    [Illuminate\Database\QueryException]                                         
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'hobi' d  
  oesn't exist in table (SQL: alter table `hobi_siswa` add constraint `hobi_s  
  iswa_hobi_foreign` foreign key (`hobi`) references `hobi` (`id`) on delete   
  cascade on update cascade)                                                   



  [PDOException]                                                               
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'hobi' d  
  oesn't exist in table             

据说是终端,但我很惊讶和困惑为什么同样可以 padahah 它的目的是关键关系。

  <?php

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

class CreateTableHobiSiswa extends Migration
{
    public function up()
    {
        //create table hobi siswa
        Schema::create('hobi_siswa', function (Blueprint $table) {
            $table->integer('id_siswa')->unsigned()->index();
            $table->integer('id_hobi')->unsigned()->index();
            $table->timestamps();

            //set PK
            $table->primary(['id_siswa', 'id_hobi']);

            //set FK hobi siswa --- siswa
            $table->foreign('id_siswa')
                  ->references('id')
                  ->on('hobi')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

            //Set FK Hobi_siswa ---hobi
            $table->foreign('hobi')
                  ->references('id')
                  ->on('hobi')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });

    }

    public function down()
    {
        Schema::drop('hobi_siswa');
    }
}

它是 createTableHobiSiswa 我做我想迁移的事

<?php

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

class CreateTableHobi extends Migration
{

    public function up()
    {
        Schema::create('hobi', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nama_hobi');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('hobi');
    }
}

这与 createTableHobi

相关

在我看来,您在第二个外键链中为 foreign() 提供的值引用了列 hobi,而 table 上的列实际上是 id_hobi.

尝试更改此部分:

//Set FK Hobi_siswa ---hobi
$table->foreign('hobi')
      ->references('id')
      ->on('hobi')
      ->onDelete('cascade')
      ->onUpdate('cascade');

改为:

//Set FK Hobi_siswa ---hobi
$table->foreign('id_hobi') //reference the column on this table correctly
      ->references('id')
      ->on('hobi')
      ->onDelete('cascade')
      ->onUpdate('cascade');