运行 artisan migrate 时出现错误
首先,我想运行多对多关系,并向多对多关系添加一个表,迁移时发生的情况是终端上出现错误。
[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
列,而表上的列实际上是 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');
关于mysql - LARAVEL 迁移错误 SQLSTATE[42000] "exist in table",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461780/