General error: 1215 Can not add foreign key constraint

3

I'm 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 Can not 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 Can not add   foreign key constraint

The tables that I'm trying to associate exist with and with the respective primary keys autoincrement.

    
asked by anonymous 23.11.2017 / 20:53

1 answer

4

It is wrong, that is, inverted, the correct one is

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

Since the references method places the field name that will construct the relationship and on method is the table name .

23.11.2017 / 20:57