I get an error when creating one-to-many migration with users table and generos_usuarios.
Migration users:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('apellidos');
$table->string('dni');
$table->string('celular1');
$table->string('celular2')->nullable();;
$table->string('convencional')->nullable();;
$table->string('estado');
$table->string('rol');
$table->string('email1');
$table->string('email2')->nullable();;
$table->string('ext_foto')->nullable();
//$table->string('genero_id')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreignId('genero_id')->nullable()
->constrained('generos_usuarios')
->cascadeOnUpdate()
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Migration genera_usuarios .
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class GenerosUsuarios extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('generos_usuarios', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nombre');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('generos_usuarios');
}
}
Photo of all my migrations.
Photo of Error in console:
First, the migration that creates the users is executed and then the migration of genders_users , so when trying to create the foreignId gender_id , it is not possible because the table it refers to (genders_usuarios) does not exist yet.
What you can do is change the name of the migration that creates the users (Place it in the name with a date greater than the one of genres) so that the migration of genres is executed first