Laravel 迁移无法添加外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33633684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel migration can't add foreign key
提问by Roemer Bakker
I'm trying to write a laravel database migration but I'm getting the following error about a foreign key:
我正在尝试编写 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
The categories
and subcategories
tables do get created but the foreign key doesn't. Here's my migration:
在categories
与subcategories
表确实会创建,但外键不。这是我的迁移:
<?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');
}
}
Any ideas? Thanks!
有任何想法吗?谢谢!
回答by Limon Monte
You should create column before creating a foreign key:
您应该在创建外键之前创建列:
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
Documentation: http://laravel.com/docs/5.1/migrations#foreign-key-constraints
文档:http: //laravel.com/docs/5.1/migrations#foreign-key-constraints
回答by Roemer Bakker
I forgot to add ->get()
to the methods I called.
我忘了添加->get()
我调用的方法。