I am using Laravel
and would like to make a relationship from the table of municipios
that contains estado_id
. The estado_id
will be related to the estado_id
of the table of estados
.
Soon after running query
, I returned the following error:
[Illuminate \ Database \ QueryException] SQLSTATE [HY000]: General error: 1005 Can not create table
banco_rep
.#sql-26f8_16b
(errno: 150 "Foreign key construct aint is incorrectly formed ") (SQL: alter tablemunicipios
add constraintmunicipios_estados_id_foreign
foreign key (estados_id
) referencesestados
(id
) on delete cascade)[PDOException] SQLSTATE [HY000]: General error: 1005 Can not create table
banco_rep
.#sql-26f8_16b
(errno: 150 "Foreign key construct aint is incorrectly formed ")
Soon I have the codes PHP
, part in which I execute and create the bank:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableMunicipiosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('municipios');
Schema::create('municipios', function (Blueprint $table) {
$table->increments('municipios_id');
$table->integer('estados_id')->unsigned();
$table->string('nome', 100);
$table->char('cep',10);
$table->foreign('estados_id')
->references('estados_id')
->on('estados')
->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('municipios');
}
}
I create the table database states:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableEstadosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('estados');
Schema::create('estados', function (Blueprint $table) {
$table->increments('estados_id');
$table->string('nome', 100);
$table->char('sigla', 2);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('estados');
}
}
Model States:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estados extends Model
{
protected $fillable = ['estados_id','nome','sigla'];
protected $dates = ['deleted_at'];
public function municipios()
{
return $this->belongsTo('App\Municipios');
}
}
Model Municipalities:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Municipios extends Model
{
protected $fillable = ['municipios_id','estados_id', 'nome', 'cep'];
protected $dates = ['deleted_at'];
public function estados()
{
return $this->hasMany('App\Estados');
}
}