-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 keyConstraint (SQL: alter tableanexos_postsadd Constraintanexos_posts_post_id_foreignForeign key (post_id) Referencespostagens(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
– Netinho Santos
I’ve tried the same and the mistake persists.
– Bruno Santos
To establish a Constraint, the fields must have the same type and size, check out how it is without created the
idof your tablepostagens, because I ran the migrations without mistakes.– Dobrychtop