Laravel迁移无法添加外键

时间:2015-11-10 15:34:08

标签: mysql database laravel migration

我正在尝试编写laravel数据库迁移,但是我收到有关外键的以下错误:

  [Illuminate\Database\QueryException]                                                                                                                                                                                                                    
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`))  



  [PDOException]                                                                                           
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table 

确实创建了categoriessubcategories表,但外键却没有。这是我的迁移:

<?php

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

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function ($table) {
            $table->increments('id')->unsigned();
            $table->string('name')->unique();
        });

        Schema::create('subcategories', function ($table) {
            $table->increments('id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->string('name')->unique();
        });
    }

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

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:45)

您应该在创建外键之前创建列:

\d+\K\.

文档:http://laravel.com/docs/5.1/migrations#foreign-key-constraints

答案 1 :(得分:2)

整数对我不起作用。相反,我使用 bigInteger 创建外键:

$table->bigInteger('category_id')->unsigned()->index()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

答案 2 :(得分:1)

我忘了将->get()添加到我调用的方法中。