Laravel 4迁移问题中的外键
我刚刚创建了一个新的 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.
相关文章