Laravel 4迁移中的外键问题 [英] Foreign keys in Laravel 4 migrations issue
问题描述
我刚刚创建了一个新的Laravel 4项目,并且发现架构生成器的外键方面发生了奇怪的事情.如果在任何迁移中都使用->foreign()
方法,则会抛出MySQL错误150和常规错误1005.根据laravel.com/docs上的文档,底部的两种情况应该起作用吗?有人知道为什么他们不这样做吗?
I've just created a new Laravel 4 project and am finding strange things happening with the foreign key aspect of the schema builder. If I use the ->foreign()
method in any of my migrations I get thrown MySQL errors 150 and general error 1005. According to the documentation at laravel.com/docs the two scenario's at the bottom should work? Anyone know why they don't?
以下方法有效:
Schema::create('areas', function($table)
{
$table->engine ='InnoDB';
$table->increments('id');
$table->integer('region_id')->references('id')->on('regions');
$table->string('name', 160);
$table->timestamps();
});
但这两个不起作用:
Schema::create('areas', function($table)
{
$table->engine ='InnoDB';
$table->increments('id');
$table->foreign('region_id')->references('id')->on('regions');
$table->string('name', 160);
$table->timestamps();
});
Schema::create('areas', function($table)
{
$table->engine ='InnoDB';
$table->increments('id');
$table->integer('region_id');
$table->foreign('region_id')->references('id')->on('regions');
$table->string('name', 160);
$table->timestamps();
});
推荐答案
检查您的id
类型. Laravel 4创建一个带有int(10)无符号的增量ID.
如果创建一个基本整数并尝试在其上放置一个外键,它将失败.
Check your id
type. Laravel 4 creates an incremental id with a int(10) unsigned.
If you create a basic integer and try to put a foreign key on it, it will fail.
如此链接,则应使用$table->unsignedInteger(YOUR_ID_NAME);
创建外部ID,以使其正常工作.
As suggested in the documentation at this link, you should create the foreign id with $table->unsignedInteger(YOUR_ID_NAME);
to make it work.
这篇关于Laravel 4迁移中的外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!