Problem when adding a FOREIGN KEY

Asked

Viewed 1,074 times

-1

Guys I’m having trouble adding a foreign key in Laravel 5.4. Follows the codes of migrations down below:

Schema::create('anexos_posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('anexo');
        $table->integer('post_id')->unsigned();
        $table->timestamps();
    });

Soon after another is executed migration adding to foreign:

Schema::table('anexos_posts', function (Blueprint $table) {
        $table->foreign('post_id')->references('id')->on('postagens');
    });

Error:

Schema::table('anexos_posts', Function (Blueprint $table) { $table->Foreign('post_id')->References('id')->on('posts'); }); In Connection.php line 647: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key Constraint (SQL: alter table anexos_posts add Constraint anexos_posts_post_id_foreign Foreign key ( post_id) References postagens (id))

In Connection.php line 449: SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint

  • I think this will help you. https://stackoverflow.com/a/23587127/4312593

  • I’ve tried the same and the mistake persists.

  • To establish a Constraint, the fields must have the same type and size, check out how it is without created the id of your table postagens, because I ran the migrations without mistakes.

1 answer

0

You can do it all at once. Follow an example of a financier I made.

Schema::create('financeiro', function (Blueprint $table) {
        $table->increments('id');
        $table->date('data');
        $table->date('vencimento');
        $table->date('data_pagamento');
        $table->enum('status', array('PROVISIONADO','EFETIVADO'));
        $table->enum('tipo_lancamento', array('CRÉDITO','DÉBITO'));
        $table->integer('pessoa_id')->unsigned();
        $table->integer('user_id')->unsigned()->nullable();
        $table->integer('filial_id')->unsigned()->nullable();
        $table->integer('modalidade_pagamento_id')->unsigned()->nullable();
        $table->integer('bancos_id')->unsigned()->nullable();
        $table->float('valor')->nullable();
        $table->float('descontos')->nullable();
        $table->float('juros')->nullable();
        $table->float('valor_cobrado')->nullable();
        $table->text('historico')->nullable();
        $table->text('observacoes')->nullable();
        $table->foreign('pessoa_id')->references('id')->on('pessoas');
        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('filial_id')->references('id')->on('equipe');
        $table->foreign('modalidade_pagamento_id')->references('id')->on('modalidade_pagamento');
        $table->foreign('bancos_id')->references('id')->on('bancos');
        $table->timestamps();
    });

Browser other questions tagged

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