Laravel 4 - 迁移和外键问题

时间:2014-11-16 09:20:00

标签: php mysql laravel-4 foreign-keys

我想使用迁移来创建2个表:usersposts 这是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') 为什么?!我怎么能让它发生?

1 个答案:

答案 0 :(得分:1)

为了将来引用具有此问题的其他人,修复很简单:允许您的外键列可以为空。