duanchuang1935
duanchuang1935
2016-02-13 23:16

Laravel外键有什么问题?

已采纳

I'm trying to create a foreign key using Laravel's migration.

 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');

    });

I'm getting the following error, when I do php artisan migrate

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter ta ble laravel_articles add constraint articles_user_id_foreign foreign key (user_id ) references laravel_users (id) on delete cascade) `

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqiang3768 douqiang3768 5年前

    You have a typo in the method name. It's supposed to be unsigned() not 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();
    });
    

    The Schema Builder uses Fluent to chain the methods, which doesn't throw an exception even if the chained method unsinged doesn't exist. The articles table would still be created despite the typo, but the user_id column would be a signed integer, and since the id column in the users table is an unsigned integer it will prevent the constraint from being created.

    点赞 评论 复制链接分享