I am trying to apply a foreign Key to column user_id, related with ID of table users
I have tried doing it by migrations and in workbench and this error keeps coming:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
this is the mysql:
ALTER TABLE `dh_booky`.`books`
ADD CONSTRAINT `books_user_id_foreign`
FOREIGN KEY (`user_id`)
REFERENCES `dh_booky`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
1st migration books:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('title_id')->unsigned();
$table->foreign('title_id')->references('id')->on('titles');
$table->bigInteger('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('authors');
$table->string('image')->nullable();
});
}
Update migration books:
class UpdateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
//php artisan make:migration update_votes_table
});
User migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
});
}