【问题标题】:Laravel 4 - migration and foregin keys issueLaravel 4 - 迁移和外键问题
【发布时间】:2015-01-13 08:20:54
【问题描述】:

我想使用迁移来创建 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') 为什么?!我怎样才能让它发生?

【问题讨论】:

  • 你用的是什么数据库?
  • 我相信$table->increments() 创建的列与$table->unsignedInteger() 略有不同,并且要设置外键约束,列必须完全相同。尝试在没有外键的情况下运行迁移,看看列是否匹配(不包括自动增量)。
  • 当心我的问题伙伴:如果我删除onDelete->('SET NULL') 将没有问题并且迁移工作
  • 您是否尝试过将外键列设置为允许为空?
  • 就是这样!!!感谢您的建议,请发表您的答案,让我选择您的观点作为最佳答案伴侣

标签: php mysql laravel-4 foreign-keys


【解决方案1】:

为了将来参考其他有此问题的人,解决方法很简单:允许您的外键列可以为空。

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2014-03-11
    • 2014-08-09
    • 1970-01-01
    • 2013-08-27
    • 2020-08-01
    • 2013-06-14
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多