如何在Laravel 5.3中输入外键

时间:2017-01-16 10:33:05

标签: laravel eloquent laravel-5.3

我使用Laravel 5.3和MySQL 我将在论坛上创建外键并在用户ID上引用 用户迁移

{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 60)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

论坛中的迁移

{
    Schema::create('forums', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('thread');
        $table->text('deskripsi');
        $table->timestamps();
    });

    Schema::table('forums', function(Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users');
    });
}

但我发现错误

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dbkelas`.`forums`, CONSTRAINT `forums_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: insert into `forums` (`thread`, `deskripsi`, `updated_at`, `created_at`) values (Matematika Diskrit, Bagaimana ya, 2017-01-14 15:10:18, 2017-01-14 15:10:18))

你有解决方案吗?

1 个答案:

答案 0 :(得分:2)

我认为您的迁移代码需要更新如下:

Schema::create('forums', function(Blueprint $table) {
       $table->increments('id');
       $table->integer('user_id')->unsigned();
       $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
       $table->string('thread');
       $table->text('deskripsi');
       $table->timestamps();
   });

希望这对你有用!