Laravel 4 Migrations抛出1072错误

时间:2013-06-04 21:44:22

标签: php mysql laravel laravel-4

我在一个新的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();
    });
  }
}

2 个答案:

答案 0 :(得分:17)

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

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');
    });
  }
}

答案 1 :(得分:4)

并且不要忘记将外键设为无符号。

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