Problem when migrating tables with Laravel (Foreign key constraint is incorrectly formed)

0

Migration of the student table

public function up()
{
    Schema::create('alumno', function (Blueprint $table) {
       $table->increments('id');
        $table->string('nombre');
        $table->string('email');
        $table->timestamps();
    });
}

Migration of the note table

public function up()
{
    Schema::create('notas', function (Blueprint $table) {
        $table->increments('id');
        $table->string('curso');
        $table->string('alumno_id');
        $table->timestamps();

        $table->foreign('alumno_id')
                            ->references('id')->on('notas')
                            ->onDelete('cascade');
    });
}
    
asked by CARLOS OMAR BLANCO RODRÍGUEZ 05.03.2018 в 05:59
source

1 answer

1

the details are:

  • The field that will serve as a foreign key must be integer and not string as you had it
  • In addition to type unsigned , the other detail is that the foreign key should be referencing the student table, since it obtains the primary key
  • SAMPLE OF THE CODE

    public function up()
    {
        Schema::create('notas', function (Blueprint $table) {
            $table->increments('id');
            $table->string('curso');
            $table->integer('alumno_id')->unsigned();    
            $table->foreign('alumno_id')
                  ->references('id')->on('alumno')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            $table->timestamps();
        });
    }
    
      

    Always consider that the field that will serve as a foreign key   recognize it as unsigned , because this method will help you to that   column does not have negative ids records.

         

    I also do the observation, in your student table the primary key   is of type integer and auto incremental but in your table you note the key   foreign you declare it as string and that is incorrect since they are not   of the same type of data; so please better declare them as   integers and unsigned .

        
    answered by 05.03.2018 / 06:08
    source