In my migration operation I intend to create two tables: hunter and master, the table master contains the foreign key of hunter. When running php artisan migrate the following error occurs: SQLSTATE[HY000]: General error: 1005 Can't create table teste.master (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table master add constraint master_id_hunter_foreign foreign key (id_hunter) references id_hunters (id)), I don't understand what mistake i'm making.
Not to mention that when using php migration:rollback the master and migrations tables is not deleted.
Migration hunter
public function up()
{
Schema::create('hunter', function (Blueprint $table) {
$table->id('id_hunter');
$table->string('name_hunter', 50);
$table->integer('age_hunter');
$table->decimal('weight_hunter', 5,2);
$table->decimal('heigth_hunter', 3,2);
$table->string('type_hunter', 30);
$table->string('nen_hunter', 30);
$table->string('type_blood', 3);
$table->timestamp('date_insert')->useCurrent();
$table->timestamp('date_update')->useCurrent()->useCurrentOnUpdate();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('hunter');
}
Migration master
public function up()
{
Schema::create('master', function (Blueprint $table) {
$table->id('id_master');
$table->foreignId('id_hunter')->constrained();
$table->string('name_master', 50);
$table->string('nen_master', 30);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('master');
}
CodePudding user response:
add this to inside you master migration $table->foreign('id_hunter')->references('id_hunter')->on('hunter')->onDelete('cascade');
CodePudding user response:
In the migrate hunter file:
$table->id(); // Removed 'id_hunter'
In the migrate master file:
$table->id(); // Removed 'id_master'
$table->foreignId('id_hunter')->constrained('hunter'); // Added ´hunter´ in constrained()
