Laravel 5.4 Migrations?

Asked

Viewed 59 times

1

I’m learning Laravel 5.4, when I will create a related table one to one is not creating the foreign key, but creates tables normally.

My Migrations:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email',80)->unique();
            $table->string('password');
            $table->integer('unidade_id')->unsigned();
            $table->foreign('unidade_id')->references('id')
                  ->on('unidades')->onDelete('cascade');
            $table->rememberToken();
            $table->timestamps();
        });
    }    
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

<?php

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

class CreateUnidadesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('unidades', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nome',60);
            $table->string('cep',10);
            $table->string('logradouro',100);
            $table->string('numero',10);
            $table->string('bairro',60);
            $table->string('cidade',60);
            $table->char('uf',2);
            $table->string('telefones',30);
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('unidades');
    }
}
  • Any error is reported?

  • What mistake are you making?

  • No, you make a mistake, it just doesn’t create the relationship

1 answer

0

For the creation of Foreign you need to first run the table migrate units and after that migrate the table users.

php artisan db:see --class=CreateUnidadesTable

php artisan db:see --class=CreateUsersTable
  • Okay, I’ll test it like this!

Browser other questions tagged

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