Laravel外键有什么问题?

时间:2016-02-13 23:16:18

标签: php mysql laravel

我尝试使用Laravel的迁移创建外键。

 Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsinged();
        $table->string('title');
        $table->longText('body');
        $table->timestamp('published_at');
        $table->timestamps();

    });


    Schema::table('articles', function($table) {
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

    });

当我php artisan migrate

时,我收到以下错误
  

[照亮\数据库\ QueryException]
  SQLSTATE [HY000]:常规错误:1215无法添加外键约束   (SQL:alter ta ble laravel_articles添加约束   articles_user_id_foreign外键(user_id)引用   关于删除级联的laravel_usersid)``

1 个答案:

答案 0 :(得分:4)

方法名称中有拼写错误。它应该是unsigned()而不是unsinged()

Schema::create('articles', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('title');
    $table->longText('body');
    $table->timestamp('published_at');
    $table->timestamps();
});

Schema Builder使用Fluent链接方法,即使链接方法unsinged不存在也不会抛出异常。尽管存在拼写错误,仍会创建articles表,但user_id列将是有符号整数,并且id表中的users列是无符号整数它将阻止创建约束。