Back

Foreign Key makes Problems


Helge Meiering posted 5 months ago

Hello, I would like to program an inventory system and need 3 tables for it. These can also be generated via artisan without a foreign key. But as soon as I want to add a foreign key, I get the following error message.

SQLSTATE[HY000]: General error: 1005 Can't create table `inventar`.`#sql-fd4_141` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `items` add constraint `items_lend_foreign` foreign key (`lend`) references `lending` (`id`))

Here my Code:

Item Table

Schema::create('items', function (Blueprint $table) {
            $table->string('barcode');
            $table->primary('barcode');

            $table->string('name');
            $table->string('description')->nullable();
            $table->string('room')->nullable();
            $table->string('status')->nullable();
            $table->string('annotation')->nullable();
            $table->string('image')->nullable();
            $table->integer('lend')->unsigned()->nullable();
            $table->string('manufactor')->nullable();



            $table->timestamps();
        });

        Schema::table('items',function ($table){
            $table->foreign('lend')->references('id')->on('lending');

        });

Lending Table

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


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

            $table->dateTime('startdate');
            $table->dateTime('enddate');
            $table->timestamps();
        });

        Schema::table('lending',function ($table){
            $table->foreign('barcode')->references('barcode')->on('items');
            $table->foreign('personid')->references('personid')->on('persons');

        });

Persons-Table

 Schema::create('persons', function (Blueprint $table) {
            $table->integer('personid')->unsignd()->primary();

            $table->string('firstname');
            $table->string('lastname');
            $table->string('email');
            $table->string('annotation')->nullable();
            $table->timestamps();
        });

I've also googled, but found no solution that works for me.

Hector Tornos replied 5 months ago

I always use Laravel "best practice" notation.

Model: Item Table: items PK: id FK: lendings_id (lendings is the name of related table)

Model: Lending Table: lendings PK:id FK:person_id

Model: Person Table: persons PK: id


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us