Laravel cannot add foreign key constraint - php

When I'm trying to set a foreign key constraint in laravel 5 with migrations I receive the error:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General
error: 1215
Cannot add foreign key constraint (SQL: alter table
rittenregistratie add co nstraint
rittenregistratie_karakterrit_id_foreign foreign key
(karakterrit_id) references karakterrit (id) on delete
cascade) [PDOException] SQLSTATE[HY000]: General error: 1215
Cannot add foreign key constraint D:\wamp\www>
But I have now idea why??? The order of migrating is right so why do I receive this error? The table rittenregistratie has a foreign key called karakterrit_id this is the primary key in the table karakterrit.
This is my migration rittenregistratie:
public function up()
{
Schema::create('rittenregistratie', function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->timestamps('datum');
$table->integer('beginstand');
$table->integer('eindstand');
$table->text('van');
$table->text('naar');
$table->text('bezoekadres');
$table->text('geredenroute');
$table->integer('karakterrit_id')->default(1);
$table->text('toelichting');
$table->integer('kilometerszakelijk');
$table->integer('kilomteresprive');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('karakterrit_id')
->references('id')
->on('karakterrit')
->onDelete('cascade');
});
}

Add
$table->integer('karakterrit_id')->unsigned()->default(1);
Have you created the users Table and karakterrit that you used in your query. If you have both tables, check the creation date of the migration files they both should be created before other table that references them.
Another problem might be MyISAM which does not support. Instead use InnoDB
DB::statement('ALTER TABLE categories ENGINE = InnoDB');

One common problem with even Laravel 8 is that the table on which the foreign_id is being set up is created earlier. So when migrations run, they run in order and can't find foreign id referenced table. If you see that happen to change the name of the second table to an earlier date and you are sorted.
So say rename 2020_12_04_081855_create_developers_table.php to 2020_12_03_081855_create_developers_table.php.
That will take care of it. Remember the date should be earlier than the first table.

for the most of the case the referenced column must be either primary key or have unique key from my findings

Laravel 8: I renamed my two migration files with the foreign key constraints to the latest date. This solved for me.

Related

Laravel - MySQL - Add foreign key to an existing column - Duplicate foreign key constraint name

I have a Laravel app and I have two tables, invoices and items. My items already have a column invoice_id, but it's not a foreign key.
When I check the structure in SequelAce, it shows invoice_id is a MUL key, in the index list below it lists items_invoice_id_index (foreign keys are shown as ..._foreign).
I tried the combination of the following:
Schema::table('items', function (Blueprint $table) {
$table->index('invoice_id'); // same error even if removed
$table->unsignedInteger('invoice_id')->change(); // same error even if removed
$table->integer('invoice_id')->unsigned()->index()->change(); // same error even if removed
$table->foreign('invoice_id')->references('id')->on('invoices');
});
But it gives me the following error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name 'items_invoice_id_foreign' (SQL: alter table `items` add constraint `items_invoice_id_foreign` foreign key (`invoice_id`) references `invoices` (`id`))
My Laravel version is 5.6.
When I check table info, I see this:
PRIMARY KEY (`id`),
KEY `items_invoice_id_index` (`invoice_id`),
CONSTRAINT `items_invoice_id_foreign` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`)
Does it mean that it's already foreign key? But I don't see any relationship when I generate a diagram. How do I fix this? I need to make a relation but not lose any data.
I see that the exception message is very clear: the index method marks the column as a foreign key so, when we say $table->index('invoice_id') this mark the invoice_id as a foreign key (The column name must exist before executing this line), and this line $table->integer('invoice_id')->unsigned()->index()->change() also makes invoice_id as a foreign key again, and this invalid approach so, your schema must be like so:
Schema::table('items', function (Blueprint $table) {
$table->unsignedBigInteger('invoice_id');
$table->foreign('invoice_id')->references('id')->on('invoices');
});
In case you want to use the index method, your schema must be like so:
Schema::table('items', function (Blueprint $table) {
$table->unsignedBigInteger('invoice_id');
$table->index('invoice_id'); // You can not execute this line before declaring the column name before
});
or briefly, you can do something like that
Schema::table('items', function (Blueprint $table) {
$table->foreignId('invoice_id')->constrained()->cascadeOnDelete();
});

Unknown (MEDIUMINT?) issue with Foreign Keys in Laravel 5.8 Migration [duplicate]

This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 3 years ago.
I am having trouble adding a MEDIUMINT foreign key constraint to a table.
I know it works, in the BASE TABLE the organization_id also references a MEDIUMINT. The first foreign key in the FOREIGN TABLE works, but the second does not.
Things I know for sure:
both the parent table and the child table have unsignedMediumInteger;
foreign column is created; and
the key is added after the parent table and foreign column creation.
Things I have tried:
changing $table->unsignedMediumInteger('customer_id'); to $table->mediumInteger('customer_id')->unsigned();
seperating the foreign key from the Schema::create('numberblocks') into Schema::table('numberblocks') on the same migration;
changing the datatype to INT, SMALLINT;
chaning the name from customer_id to c_id in the child table; and
setting the foreign key to its own migration.
BASE TABLE
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->unsignedMediumInteger('organization_id');
$table->unsignedMediumInteger('customer_id');
$table->string('customer_domain');
$table->timestamps();
// Foreign Keys
$table->foreign('organization_id')->references('id')->on('organizations');
});
FOREIGN TABLE
Schema::create('numberblocks', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('group_id')->index();
$table->unsignedMediumInteger('customer_id');
$table->unsignedMediumInteger('order_id');
$table->string('number', 15);
$table->timestamps();
// Foreign Keys
$table->foreign('group_id')->references('id')->on('groups');
$table->foreign('customer_id')->references('customer_id')->on('customers');
});
Everything I have tried ends up with the same error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'db'.'#sql-1a78_2a6'
(errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'numberblocks' add constraint 'numberblocks_customer_id_foreign'
foreign key ('customer_id') references 'customers' ('customer_id'))```
My question:
Does anyone else know a way to get this working?
yes it will as the error says
General error: 1822 Failed to add the foreign key constaint. Missing
index for constraint 'numberblocks_customer_id_foreign' in the refere
nced table 'customers'")
So try adding
$table->index(['customer_id']);
in the customers migration and will fix the issue
if not Kindly Comment below

Table not found when seeding

Below are my migrations
The users table have a relation with the customer table
In user:
$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');
When i call php artisan migrate:refresh --seed, artisan given me the following error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `users` add constraint `users_customer_id_foreign` foreign ke
y (`customer_id`) references `customers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Because the customers table does not exists... (obvious)
Is there a way to solve this problem? I know changing the date of the files will fix this but there should be a beter approach
You have to create the table you're referencing to before adding the foreign key. A solution would be to remove the foreign key constraint from your user table migration and create a new migration which adds the foreign key constraints.
Try to make it separately.
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->integer('costumer_id')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->foreign('costumer_id')->references('id')->on('costumers');
});
}
Another thing you can try(since laravel 5.3):
unsignedInteger('column_name') instead of ('column_name')-unsigned()
If you had set one field as "Unsigned" and other one not. Once you should set both columns to Unsigned it works.

mysql foreign key error in Laravel 5.1

I have created two migrations:
Migration 1
Schema::create('responders', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->double('latitude', 10, 6);
$table->double('longitude', 10, 6);
$table->timestamps();
});
Migration 2
Schema::create('devices', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->string('device_id');
$table->string('device_token');
$table->timestamps();
$table->foreign('user_id')
->references('user_id')
->on('responders')
->onDelete('cascade');
});
When I start migration the error message is being thrown:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table devices add constraint devices_user_id_foreign
foreign key (user_id) references responders (user_id) on delete
cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
I specifically took care that the data types are the same. In this case both are of type string. Why does the foreign key can't be established?
A foreign key is a column (or columns) that references a column (most
often the primary key) of another table. The purpose of the foreign
key is to ensure referential integrity of the data. In other words,
only values that are supposed to appear in the database are permitted.
Here user_id in responders table isn't a key that's why it's showing this error.

How to run php artisan migrate on a db with a lot of tables and data without previous migrations in Laravel 4?

I have created a lot of tables and I have a lot of data in my db's tables already.
I haven't used migrations so far. But right now I would like to, in this case where I need to set foreign keys using this code:
public function up()
{
Schema::create('role_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
But If I run php artisan migrate I get this error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `role_user` add constraint role_user_role_id_foreign foreign
key (`role_id`) references `roles` (`id`) on delete cascade)
migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--pac
kage[="..."]] [--pretend] [--seed]
I have roles and users table already and id is set as the primary key.
Any idea how to make this auto creation of the table from the schema in the migration file in my db happen?

Categories