How to solve foreign key error 150 in migration with laravel?

4

I'm having trouble creating the foreign key in migration.

I'm working with PHP, LARAVEL 5.3 and MYSQL. You are giving me the following error:

Below is my code:

Table Migration of the categs

class CreateCategsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categs', function (Blueprint $table) {
            $table->increments('id');
            $table->text('nome_cat');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categs');
    }
}

Product Table Migration

class CreateProdutosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produtos', function (Blueprint $table) {
            $table->increments('id');
            $table->text('nome');
            $table->text('descricao');
            $table->integer('categs_id');
            $table->foreign('categs_id')->references('id')->on('categs');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('produtos');
    }
}

Model categs

use Illuminate\Database\Eloquent\Model;

class categ extends Model
{
    //Relacionamento 1:n Categoria dos produtos

    public function produtos()
    {
        return $this->hasMany('App\produtos');
    }
}

Model products

use Illuminate\Database\Eloquent\Model;

class Produtos extends Model
{
    //
    public function categoria()
    {
        return $this->belongsTo('App\categ');
    }
}
    
asked by anonymous 28.07.2017 / 12:49

3 answers

3

When you run the seed command. The laravel adopts the order of the files as line of execution from top to bottom. That is, migrate of categs must be before migrate of produtos .

For example, the companies table is 1-N with banks , then migrate companies should be above migrate banks .

Schema::create('banks', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->integer('account');
    $table->integer('bank_agency');
    $table->integer('company_id')->unsigned(); //compaines_table.php
    $table->timestamps();

    $table->foreign('company_id')->references('id')->on('companies');
});
    
28.07.2017 / 13:48
2

I was able to solve the problem in the following way: in migration products, I changed

$table->integer('categs_id'), 

for

$table->unsignedinteger('categs_id')
    
29.07.2017 / 00:10
0

Another way to create the relationship field:

$table->integer('categs_id', false, true);
    
06.08.2017 / 08:20