5

我在一个新的 Laravel 4 项目中有几个迁移。一个用于区域,另一个用于区域。每个区域都有多个区域,区域属于区域。

我曾多次使用 Laravel 4 和迁移功能,但之前从未遇到过这个问题。当我php artisan migrate:install随后运行时,php artisan migrate出现以下错误:

$ php artisan migrate
  [Exception]
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'region_
  id' doesn't exist in table (SQL: alter table `areas` add constraint areas_r
  egion_id_foreign foreign key (`region_id`) references `regions` (`id`)) (Bi
  ndings: array (
  ))
migrate [--bench[="..."]] [--database[="..."]] [--path[="..."]] [--package[="...
"]] [--pretend] [--seed]

// 区域迁移

class CreateRegionsTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    // Creates the regions table
   Schema::create('regions', function($table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('name', 160)->unique();
        $table->timestamps();
    });
  }
}

// 区域迁移

class CreateAreasTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    // Creates the cemeteries table
    Schema::create('areas', function($table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->foreign('region_id')->references('id')->on('regions');
        $table->string('name', 160)->unique();
        $table->timestamps();
    });
  }
}
4

2 回答 2

16

您必须创建与外键相关的列:

class CreateAreasTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    // Creates the cemeteries table
    Schema::create('areas', function($table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');

        $table->integer('region_id')->unsigned();
        $table->foreign('region_id')->references('id')->on('regions');

        $table->string('name', 160)->unique();
        $table->timestamps();

    });
  }
}

有时(取决于您的数据库服务器)您必须分两步创建外键:

class CreateAreasTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    // Create the table and the foreign key column
    Schema::create('areas', function($table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');

        $table->integer('region_id')->unsigned();

        $table->string('name', 160)->unique();
        $table->timestamps();

    });

    // Create the relation
    Schema::tabe('areas', function($table)
    {
        $table->foreign('region_id')->references('id')->on('regions');
    });
  }
}
于 2013-06-04T21:51:18.027 回答
4

并且不要忘记使外键无符号。

         $table->integer('region_id')->unsigned();
于 2013-08-16T09:24:38.923 回答