2017-01-16 66 views
0

我使用Laravel 5.3和MySQL 我会做出对用户ID 迁移的论坛和引用外键的用户如何Laravel外键5.3

{ 
    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)) 

你有什么解决方案吗? ?

+0

你有没有试过这个http://stackoverflow.com/questions/20801754/add-foreign-key-to-existing-table-laravel-4 – vijaykumar

+0

当你尝试向论坛添加新的数据时,你有错误吗?需要user_id – Iman

+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(); 
    }); 

希望这对你的工作!

+0

谢谢,我会尝试 – Feboy

+0

@FebbyNurfitriyani:它的工作..? –

+0

谢谢!是的,它的工作。 – Feboy