Search code examples
sqllaravelartisan-migrate

getting following error " 150 "Foreign key constraint is incorrectly formed"" on the console


I've checked several times against other projects and I just cannot see what's wrong.

I attach my code:

        Schema::table('datos', function (Blueprint $table) {

            $table->bigInteger('sensor_id')->change();
            $table->foreign('sensor_id')->references('id')->on('sensores')->nullable();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('datos', function (Blueprint $table) {
        $table->dropForeign(['sensor_id']);
    });
}

Solution

  • Your function will be look like :

    public function up()
        {
            Schema::create('datos', function (Blueprint $table) {
                $table->bigIncrements('id');
    
                $table->bigInteger('sensor_id')->unsigned();
                $table->foreign('sensor_id')->references('id')->on('sensores')->onDelete('cascade');
    
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('datos');
        }