laravel错误150外键约束形成错误

时间:2017-04-09 13:35:42

标签: php laravel

我收到错误:

  

SQLSTATE [HY000]:常规错误:1005无法创建表   monkeybussiness#sql-db0_17(错误:150“外键关键词   形成错误“)

虽然据我所知,列是相同的。为什么会这样?

事件迁移文件:

<?php

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

class CreateEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('afspraak_id');
            $table->timestamps();
            $table->string('titel');
            $table->integer('persoon_id');
            $table->foreign('persoon_id')->references('persoon_id')->on('personen');
        });
    }

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

Personen迁移文件:

<?php

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

class Personen extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('personen', function (Blueprint $table) {
            $table->increments('persoon_id');
            $table->timestamps();
            $table->string('voornaam');
            $table->string('achternaam');
            $table->string('email')->unique();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

我尝试->unsigned(),但这也不起作用。

2 个答案:

答案 0 :(得分:1)

问题是事件表是先创建的。我不得不更改文件名的日期,以便它位于persoon表之后。之后它起作用了。

答案 1 :(得分:0)

It seems you have copied pasted without editing your migration files. Your personen migrations has all the same data as 'events'. If that's the case in your application, then surely the foreign key cannot work because the table does not exist.

If it just an error of copy, make sure you put the correct table name here

 $table->foreign('persoon_id')->references('persoon_id')->on('personen');
 //table name should be 'personens' ?

Can you try to alias it?

$table->foreign('persoon_id', 'fk_persoon_id')->references('persoon_id')->on('personen')
->onDelete('no action')
->onUpdate('no action');