TiagoSilvaPereira / vemto2-issues

Repository to track Vemto 2 Issues
5 stars 0 forks source link

relationship causes mysql error on migrating #193

Open ankorinek opened 1 month ago

ankorinek commented 1 month ago

I've created 2 tables: organization and person. Each person belongs to one organization.

When migrating, I get

SQLSTATE[HY000]: General error: 3780 Referencing column 'organization_id' and referenced column 'id' in foreign key constraint 'person_organization_id_foreign' are incompatible. (Connection: mysql, SQL: alter table person add constraint person_organization_id_foreign foreign key (organization_id) references organization (id) on delete cascade on update cascade)

Code for organization:

<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('organization', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();
        });
    }

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

Code for person:

<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('person', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->bigInteger('organization_id');
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();

            $table
                ->foreign('organization_id')
                ->references('id')
                ->on('organization')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('person');
    }
};
TiagoSilvaPereira commented 4 weeks ago

Hi @ankorinek, your FK is not unsigned, but Foreign keys must be unsigned. I recommend letting Vemto create the FKs (you add relationships to the models, and Vemto automatically creates them). I'll keep this issue open as I pretend to add an alert on Vemto when an FK is not correctly formulated