【发布时间】:2015-01-13 08:20:54
【问题描述】:
我想使用迁移来创建 2 个表:users 和 posts
这是我的create_users_table 代码:
Schema::create('users', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('username',50);
$table->string('password',100);
});
之后我想创建create_posts_table:
Schema::create('posts',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('title',100);
$table->text('content');
$table->unsignedInteger('users_id');
$table->foreign('users_id')->references('id')->on('users')->onDelete('SET NULL')->onUpdate('CASCADE');
$table->timestamps();
});
这是我的问题:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table 'posts' add constraint posts_users_id_foreign foreign key ('u
sers_id') references 'users' ('id') on delete SET NULL on update CASCADE)
我查看了我的代码,发现无法添加 onDelete('SET NULL')
为什么?!我怎样才能让它发生?
【问题讨论】:
-
你用的是什么数据库?
-
我相信
$table->increments()创建的列与$table->unsignedInteger()略有不同,并且要设置外键约束,列必须完全相同。尝试在没有外键的情况下运行迁移,看看列是否匹配(不包括自动增量)。 -
当心我的问题伙伴:如果我删除
onDelete->('SET NULL')将没有问题并且迁移工作 -
您是否尝试过将外键列设置为允许为空?
-
就是这样!!!感谢您的建议,请发表您的答案,让我选择您的观点作为最佳答案伴侣
标签: php mysql laravel-4 foreign-keys