-1
Hello! I need to add a new table in an existing comic. I use the Laravel Framework and I would like to do this via Migration, but every time I try it makes a mistake and I don’t know what I might be doing wrong. I created a model called City that contains the relationship with the Neighborhood Model:
Model da Cidade:
public function bairros()
{
return $this->hasMany(Bairro::class, 'tb_cidades_id');
}
Model do Bairro:
public function cidade()
{
return $this->belongsTo(Cidade::class, 'tb_cidades_id');
}
Migration to Add to Table of Cities:
public function up()
{
Schema::create('tb_cidades', function (Blueprint $table) {
$table->increments('id');
$table->string('cidade', 60);
$table->string('estado', 2);
$table->timestamps();
});
}
Migration to Add Foreing Key to Neighborhood Table:
public function up()
{
Schema::table('tb_bairros', function (Blueprint $table) {
$table->integer('tb_cidades_id')->unsigned();
$table->foreign('tb_cidades_id')->references('id')->on('tb_cidades');
});
}
The mistake:
Illuminate Database Queryexception : SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot add or update a Child Row: a Foreign key strainCont fails (
db_xxx
.#sql-cc0_10
, CONSTRAINTtb_bairros_tb_cidades_id_foreign
FOREIGN KEY (tb_cidades_id
) REFERENCEStb_cidades
(id
)) (SQL: alter tabletb_bairros
add Constrainttb_bairros_tb_cidades_id_foreign
Foreign key (tb_cidades_id
) Referencestb_cidades
(id
))
Could someone help me?
Do your tables already have data? If yes check if in Neighborhoods there is any reference to a non-existent city.
– anonimo
Yes, all of them. This city table is new, it will be reset and I will add the data via Seeder. Now in the table Neighborhoods there is nothing that links both Tables, just an attribute called city, but has nothing to do with the new table.
– Kau
Not what the error message says.
(SQL: alter table tb_bairros add constraint tb_bairros_tb_cidades_id_foreign foreign key (tb_cidades_id) references tb_cidades (id))
. The fieldtb_bairros.tb_cidades_id
referencetb_cidades.id
.– anonimo