1

Tengo un error al generar las FKs de mis tablas en Laravel, al generar la migración de modificador de FK arroja un error de construcción y modificación de FKs:

Es importante considerar que el orden de las migraciones es el siguiente:

  • Profiles
  • Providers
  • Users
  • Charges
  • Modificación FK Charges
  • Modificaciòn FK Users

Migración usuarios (tabla 'users')

public function up(){
Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id')->unsigned();
    $table->string('name_user', 60);
    $table->string('surname_user', 45);
    $table->integer('phone_user');
    $table->string('mail_user', 60);
    $table->string('pos_user', 60);
    $table->unsignedInteger('id_user')->unsigned();
    $table->unsignedInteger('id_profile')->unsigned();
    $table->timestamps();
    $table->softDeletes();
});

}

Modificacion FK de users

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->foreign('id_user')->references('id')->on('users');
        $table->foreign('id_profile')->references('id')->on('profiles');
    });
}

Migración Cargas (tabla 'Charges')

public function up()
{
    Schema::create('charges', function (Blueprint $table) {
        $table->bigIncrements('id')->unsigned();
        $table->integer('phone_charge');
        $table->date('date_charge');
        $table->integer('mount_charge');
        $table->unsignedInteger('id_provider')->unsigned();
        $table->unsignedInteger('id_user')->unsigned();
        $table->timestamps();
        $table->softDeletes();
    });
}

Modificación FKs de Charges

public function up()
{
    Schema::table('charges', function (Blueprint $table) {
        $table->foreign('id_provider')->references('id')->on('providers');
        $table->foreign('user_id')->references('id')->on('users');
    });
}

Migración Proveedores (tabla 'Providers')

public function up()
{
    Schema::create('providers', function (Blueprint $table) {
        $table->bigIncrements('id')->unsigned();
        $table->string('name_provider',45);
        $table->timestamps();
        $table->softDeletes();
    });
}

Migración Perfiles (tabla 'Profiles')

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->bigIncrements('id')->unsigned();
        $table->string('name_profile',45);
        $table->timestamps();
        $table->softDeletes();
    });
}

El codigo output del cmd es el siguiente:

C:\xampp\htdocs\RecotecWebAPP>php artisan migrate:fresh
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2019_06_07_023856_create_profiles_table
Migrated:  2019_06_07_023856_create_profiles_table
Migrating: 2019_06_07_023902_create_providers_table
Migrated:  2019_06_07_023902_create_providers_table
Migrating: 2019_06_07_023908_create_users_table
Migrated:  2019_06_07_023908_create_users_table
Migrating: 2019_06_07_023914_create_charges_table
Migrated:  2019_06_07_023914_create_charges_table
Migrating: 2019_06_07_034219_add_fk_to_charges_table

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `recotec`.`#sql-3a40_137` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `charges` add constraint `charges_id_provider_foreign` foreign key (`id_provider`) references `providers` (`id`))

  at C:\xampp\htdocs\RecotecWebAPP\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `recotec`.`#sql-3a40_137` (errno: 150 "Foreign key constraint is incorrectly formed")")
      C:\xampp\htdocs\RecotecWebAPP\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\RecotecWebAPP\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

Espero me puedan ayudar y gracias c:

1 respuesta 1

0

En la tabla providers estás creando un campo de tipo BigInteger, el cual implícitamente es unsigned, aquí está su código en Laravel:

/**
 * Create a new auto-incrementing big integer (8-byte) column on the table.
 *
 * @param  string  $column
 * @return \Illuminate\Database\Schema\ColumnDefinition
 */
public function bigIncrements($column)
{
    return $this->unsignedBigInteger($column, true);
}

Por consiguiente, su uso es así:

Schema::create('providers', function (Blueprint $table) {
    $table->bigIncrements('id');
    // otros campos ...

En ese orden de ideas, el tipo de campo de una llave foránea debe ser el mismo que el del campo que está referenciando, lo cual quiere decir que el campo en la tabla charges debe ser un unsigned big integer también:

public function up()
{
    Schema::create('charges', function (Blueprint $table) {
        // otros campos ...
        $table->unsignedBigInteger('id_provider');

Por último, la sintaxis de la llave foránea, la veo correcta:

public function up()
{
    Schema::table('charges', function (Blueprint $table) {
        $table->foreign('id_provider')->references('id')->on('providers');
        // otros campos
1
  • Muchas gracias Shaz, solucionaste mi problema al 100%, muy intuitiva tu respuesta. gracias de verdad ;D!
    – Moar
    el 7 jun. 2019 a las 18:16

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.