How to create Foreignkey without data with Windows

Asked

Viewed 228 times

1

I’m creating a system and I have two columns: empresas and usuarios. The usuarios.id_empresa makes is the key of empresas.id_empresa, however, some data from the two tables are filled in simultaneously and after the registration is done the other information can be inserted. But if I turn php artisan migrate without data in the table empresas error appears that cannot make this link between tables by empresas not yet having data. How to resolve this?

The record dealer will have the inputs (among relatives in which table it belongs)

Name (user name) Company (enterprises) Telephone (company) E-mail (company name) password (users)

Note that this form will popular two tables at the same time, so I need to reference usuarios.id_empresas in empresas.id_empresa.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('user_id');
        $table->integer('user_empresa')->unsigned();
        $table->string('user_nome');
        $table->string('user_email')->unique();
        $table->string('user_cpf')->unique()->nullable();
        $table->string('user_rg')->unique()->nullable();
        $table->string('user_telefone')->nullable();
        $table->string('user_senha');
        $table->boolean('user_ativo');
        $table->string('user_permissions');
        $table->integer('user_profile')->unsigned();
        $table->timestamps();
        /* $table->foreign('user_empresa')
                 ->references('empresa_id')
                 ->on('empresas')->onDelete('cascade');*/
    });
}

public function up()
{
    Schema::create('empresas', function (Blueprint $table) {
        $table->increments('empresa_id');
        $table->string('empresa_nome');
        $table->string('empresa_email')->unique();
        $table->string('empresa_cnpj_cpf')->nullable();
        $table->string('empresa_telefone');
        $table->boolean('empresa_trial')->default(1);
        $table->boolean('empresa_ativo')->default(0);
        $table->boolean('empresa_cad_completo')->default(0);
        $table->string('empresa_plano')->default(0);
        $table->date('empresa_expira');
        $table->timestamps();
    });
}
  • What is the error message?

  • SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint (SQL: a lter table users add Constraint users_user_empresa_foreign Foreign key (u 
 ser_empresa) References empresas (empresa_id) on delete)

  • I know this error gives because the companies table does not have data yet but how to solve it if I need to do the list of tables even without having data?

  • Put the Migration on

No answers

Browser other questions tagged

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