无法添加外键Laravel

时间:2017-11-07 20:19:29

标签: php mysql laravel

我有2个表(区域和类别),我想在Regions表中有一个外键这是我的迁移文件:

public function up()
{
    Schema::create('regions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('nom');
        $table->text('description');
        $table->integer('vote');
        $table->string('securite');
        $table->integer('idCat')->unsigned()->change();
        $table->foreign('idCat')->references('idCat')->on('categories');
        $table->timestamps();
         });


}
表'类别'看起来像这样:

 public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        //$table->engine = 'InnoDB';
        $table->increments('idCat');
        $table->String('description');
        $table->timestamps();
    });
}

但是我收到了这个错误:语法错误或访问冲突:1072键列'idCat'
  表中不存在(SQL:alter table regions添加约束regions_
idcat_foreign
外键(idCat)引用categoriesidCat))

残友帮帮我吧?

1 个答案:

答案 0 :(得分:0)

确保你摆脱了更改(),列还没有。以下代码对我来说非常合适......

<?php

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

class Test extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            //$table->engine = 'InnoDB';
            $table->increments('idCat');
            $table->String('description');
            $table->timestamps();
        });

        Schema::create('regions', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nom');
            $table->text('description');
            $table->integer('vote');
            $table->string('securite');
            $table->integer('idCat')->unsigned();
            $table->foreign('idCat')->references('idCat')->on('categories');
            $table->timestamps();
        });


    }

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