General error: 1215 Cannot add Foreign key Constraint

Asked

Viewed 5,901 times

3

I am trying to add a foreign key to this table with the following code block

public function up()
  {
     Schema::create('registros', function (Blueprint $table) {
        $table->increments('id');
        $table->integer( 'cliente' )->unsigned()->index();
        $table->integer( 'item' )->unsigned()->index();
        $table->decimal( 'vl_preco',10,2 );
        $table->char( 'sn_pago',1 );
        $table->integer( 'qt_compra' )->unsigned();
        $table->foreign( 'cliente' )->references( 'clientes' )->on('id') ;
        $table->foreign( 'item' )->references( 'item' )->on('id') ;
        $table->timestamps();
      });
   }

But I’m getting the following message:

[Illuminate Database Queryexception] SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint (SQL: alter table registros add Constraint registros_cliente_foreign Foreign key (cliente) References id (clientes))

[Pdoexception] SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint

The tables I’m trying to associate exist and with the primary keys auto increment repective.

1 answer

7


It is wrong, that is, reversed, the correct is

$table->foreign( 'cliente' )->references( 'id' )->on( 'clientes' ) ;

and the method references put the field name that will build relationship and method on is the table name.

References

  • 1

    Dude! That’s right... I was blinded oh kkk. Thank you so much!

  • If it is the answer of your problem could accept as reply @adventistaam

Browser other questions tagged

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