Error adding Constraint (General error 1215) - Orange

Asked

Viewed 436 times

1

I am trying to create two related tables. When trying to 'migrate' them, the error is returned: "SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint (SQL: alter table 'Companies' add Constraint companies_taxregimeid_foreign' Foreign key ('taxRegimeId') References 'tax_regimes' ('id') on delete CASCADE)".

Company - Model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    protected $table = 'companies';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'taxRegimeId',
        'managerId',
    ];

    public function manager()
    {
        return $this->belongsTo('App\User', 'managerId', 'id');
    }

    public function taxRegime()
    {
        return $this->belongsTo('App\TaxRegime','taxRegimeId', 'id');
    }
}

Company - Migration:

   <?php

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

class CreateCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('taxRegimeId')->unsigned();
            $table->integer('managerId')->unsigned();
            $table->timestamps();
        });

        Schema::table('companies', function (Blueprint $table) {
            $table->foreign('managerId')->references('id')->on('users')->onDelete('CASCADE');
        });

        Schema::table('companies', function (Blueprint $table) {
            $table->foreign('taxRegimeId')->references('id')->on('tax_regimes')->onDelete('CASCADE');
        });
    }

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

As you can see in the model, I did as in the 'managerId' that follows the same scheme as the entities' relationship (A company has a manager (manager) | A company has a tax regime (taxRegimis)). In 'managerId' it works correctly, but in 'taxRegimeId' it gives this problem that I described at the beginning. What may have caused this problem?

  • Try to play your code $table->foreign('taxRegimeId')->references('id')->on('tax_regimes')->onDelete('CASCADE'); inside the callback of the Schema::create

  • The error persists.

  • Did you put the two Foreign Keys? Another question, taxRegime and manager have a relationship N:N? If you have it you cannot do so with belongsTo have to do according to https://laravel.com/docs/5.5/eloquent-relationships#updating-Many-to-Many-relationships

  • Yes, I’ve added the two forgein Keys. The relationship of both is 1:N (A manager can manage several companies, a tax system can exist in several companies, that is 1:N same?).

  • But can’t the same regime be in several companies? If yes, it makes the relationship N:N between companies and taxation.

  • I may have confused, but a company has only one taxation system, but the same system because it exists in several other companies. For me this is 1:N (FK in the company)...

  • Got it, well the code seems to be OK. You’re running the command migration:refresh'? Se tiver, ele não vai conseguir adicionar pq o seu método downestá apenas dando umdropifeschist, isso não da permissão de remover uma tabela com constraints adicionadas. Confira no seu banco, se a tabela já não existe. Não sei se é case sensitive, mas eu sempre coloquei o CASCADE` in lowercase, is another attempt.

  • I found the problem, the order of the Migrations affects the execution. The Migration of the wheel taxation scheme after the company. When the company wheel, it does not find the tax system table, ai gives the error.

Show 3 more comments
No answers

Browser other questions tagged

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