error when relating by foreign key tables

1

I have an error when relating by foreign key, it generates the table but not the relation. I deleted the tables and I generated them again and nothing Use php artisan migrate

link

public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');

            $table->string('rude');

            $table->integer('peoples_id')->unsigned();
            
            $table->foreign('peoples_id')
            ->references('id')->on('peoples')
            ->onDelete('cascade');

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

            $table->string('name', 150);
            $table->string('firstname', 75);
            $table->string('lastname', 75);

            $table->timestamps();
        });
    }
    
asked by Carlos Enrique Gil Gil 17.08.2017 в 02:44
source

2 answers

1

The problem I see is that you are apparently creating the students table first before the peoples table, which you try to reference and therefore can not find it. Unless the error is different (in case you use a very old version of MySQL for example), the order of the migrations that you sample should be something like this:

public function up()
{
    Schema::create('peoples', function (Blueprint $table) {
        $table->increments('id');

        $table->string('name', 150);
        $table->string('firstname', 75);
        $table->string('lastname', 75);

        $table->timestamps();
    });

    Schema::create('students', function (Blueprint $table) {
        $table->increments('id');

        $table->string('rude');

        $table->integer('peoples_id')->unsigned();

        $table->foreign('peoples_id')
        ->references('id')->on('peoples')
        ->onDelete('cascade');

        $table->timestamps();
    });
}
    
answered by 17.08.2017 / 06:34
source
1

I came across a similar problem and the solution was to create the tables and then the relationships.

Whenever I create tables with migrations I first do the Schema :: create and then a Schema :: table with the relationships.

The migration is similar to this:

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        // Todos los campos
    });

    Schema::create('peoples', function (Blueprint $table) {
        // Todos los campos
    });

    Schema::table('students', function (Blueprint $table) {
      $table->foreign('peoples_id')
        ->references('id')->on('peoples')
        ->onDelete('cascade');
    }
}
    
answered by 17.08.2017 в 13:46