Ao tentar inserir uma foreign key por uma migration, eu SEMPRE tenho o mesmo erro SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (diariodebordo
.#sql-3618_a3
, CONSTRAINT users_id_cargo_foreign
FOREIGN KEY (id_cargo
) REFERENCES cargos
(id
)) (SQL: alter table users
add constraint users_id_cargo_foreign
foreign key (id_cargo
) references cargos
(id
))
Já passei horas e mais horas procurando na internet e não consigo achar uma solução
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddTabelaCargos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cargos', function (Blueprint $table){
$table->increments('id');
$table->string('nome_cargo');
$table->text('permissoes');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddIdCargoNaTabelaUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table){
$table->unsignedInteger('id_cargo');
$table->foreign('id_cargo')->references('id')->on('cargos');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}