Incorrectly formed foreign key retribution Migration

Asked

Viewed 121 times

1

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {        
        Schema::create('menu', function (Blueprint $table) {
            $table->increments('id');

            $table->string('opcao');
            $table->string('href');
            $table->boolean('session');
            $table->timestamps();
        });

        Schema::create('submenu', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('submenu_id')->index;
            $table->foreign('submenu_id')->references('id')->on('menu');
            $table->string('opcao');
            $table->string('href');
            $table->boolean('ligado');
            $table->timestamps();
        });

    }} 

is giving wrong foreign key restriction error formed. Someone can help me. This error occurs when running the command php artisan migrate.

  • Dude I created your Migration in an application I already have, and it ran normally without errors. It can print the error that occurs or something like that?

1 answer

0

Missed putting unsigned in the submenu_id so that the migration is realized, because, the primary key of the table menu is created as unsigned which means that the field only accepts positive values, so the relationship also needs to know this and configured for it. Example:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {        
        Schema::create('menu', function (Blueprint $table) {
            $table->increments('id');

            $table->string('opcao');
            $table->string('href');
            $table->boolean('session');
            $table->timestamps();
        });

        Schema::create('submenu', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('submenu_id')->unsigned();
            $table->foreign('submenu_id')->references('id')->on('menu');
            $table->string('opcao');
            $table->string('href');
            $table->boolean('ligado');
            $table->timestamps();
        });

    }
} 

Browser other questions tagged

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