【发布时间】:2014-03-12 09:29:00
【问题描述】:
这似乎是一个常见问题,但我找不到与此直接相关的答案。
我有一个用户和设计表,我正在尝试向设计表添加一个外键,以使其引用用户表上的 id。
用户表的迁移:
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
设计表的迁移:
Schema::create('designs', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->string('title');
$table->timestamps();
});
我正在尝试添加外键的迁移:
public function up()
{
Schema::table('designs', function(Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('designs', function(Blueprint $table) {
$table->dropColumn('user_id');
});
}
但我收到错误消息:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bootstrap`.`#sql-512_179`
, CONSTRAINT `designs_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: alter table `designs` add constraint designs_user_
id_foreign foreign key (`user_id`) references `users` (`id`))
我在这里做错了什么?
【问题讨论】:
-
根据您的
users迁移,id 列不是无符号的(尽管我不确定 Laravel 中的“增量”是否默认无符号,它确实应该是)所以也许这是你的问题? -
我不确定这是真的 - 当我使用增量时,它被设置为无符号(虽然在 laravel 3 中)。
标签: laravel