How to add a new table 1:N (one for many) in an existing database via Migration Laravel?

Asked

Viewed 33 times

-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, CONSTRAINT tb_bairros_tb_cidades_id_foreign FOREIGN KEY (tb_cidades_id) REFERENCES tb_cidades (id)) (SQL: alter table tb_bairros add Constraint tb_bairros_tb_cidades_id_foreign Foreign key (tb_cidades_id) References tb_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.

  • 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.

  • 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 field tb_bairros.tb_cidades_id reference tb_cidades.id.

1 answer

1

A palliative solution would be to disable the constraints

public function up()
    {
        Schema::disableForeignKeyConstraints();
        Schema::create('tb_cidades', function (Blueprint $table) {
            $table->increments('id');
            $table->string('cidade', 60);
            $table->string('estado', 2);
            $table->timestamps();
        });
        Schema::enableForeignKeyConstraints();
    }

Any Constraint in your bank is generating this error, either you redo it or temporarily disable it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.