Foreign Key Constraint incorrectly formed - Laravel - php

I have two tables "theaters" and "cubelists". The "theaters" table is already created. In the "cubelists" table,I have made "area" and "stn" as foreign keys to the table "theaters". But I get an error the foreign key constraint is incorrectly formed. But I couldn't figure out the error.
Schema::create('theaters', function (Blueprint $table) {
$table->string('theater_name');
$table->string('area_name');
$table->string('station');
$table->primary(array('theater_name','area_name','station'));
$table->text('address');
$table->bigInteger('phno');
$table->string('contact_person');
});
Schema::create('cubelists', function (Blueprint $table) {
$table->string('mvie_name');
$table->foreign('mvie_name')->references('movie_name')->on('movies');
$table->string('thtr_name');
$table->foreign('thtr_name')->references('theater_name')-
>on('theaters');
$table->string('area');
$table->foreign('area')->references('area_name')->on('theaters');
$table->string('stn');
$table->foreign('stn')->references('station')->on('theaters');
$table->primary(array('mvie_name','thtr_name','area','stn'));
$table->string('type');
$table->string('subtype');
$table->date('validity');
$table->string('show');
});
Error is
C:\xampp\htdocs\boras>php artisan migrate
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
5a` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
`cubelists` add constraint cubelists_area_foreign foreign key (`area`) reference
s `theaters` (`area_name`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
5a` (errno: 150 "Foreign key constraint is incorrectly formed")

A foreign key constraint should reference a candidate key. I don't know what cubelist means, but you probably want to reference the primary key in "theaters". That is, you probably want one foreign key constraint to reference the three columns theater_name, area_name, and station. Not individual constraints on each of those columns.
MySQL might or might not let you get away with what you originally tried to do, but don't do that anyway. Search 13.1.17.6 Using FOREIGN KEY Constraints for "does not enforce".

Related

Laravel - Cannot add foreign key constraint

I am trying to add FK 'module_id' to my table 'documents'. I have ran the following query:
public function up()
{
Schema::table('documents', function (Blueprint $table) {
$table->integer('module_id')->unsigned();
$table->foreign('module_id')->references('id')->on('modules');
});
}
The following error is being returned:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table documents add constraint
documents_module_id_foreign foreign key (module_id) references
modules (id))
I'm not sure what I'm doing wrong, I'm sure it is probably a silly mistake but I have spent a lot of time going around in circles trying to figure it out... here is what I have tried..
both tables are already created
the data types for both column's are consistent (both unsignedBigInts, 20)
I have included a picture of my DB tables, i appreciate any help.
Update:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(laravel.#sql-2cd_23, CONSTRAINT documents_module_id_foreign
FOREIGN KEY (module_id) REFERENCES modules (id)) (SQL: alter
table documents add constraint documents_module_id_foreign foreign
key (module_id) references modules (id))
The type of the column needs to be a big integer.
Schema::table('documents', function (Blueprint $table) {
$table->unsignedBigInteger('module_id');
$table->foreign('module_id')->references('id')->on('modules');
});
Update
You probably already got data in your tables, since the column can't be null the foreign key can't exists. Starting it out as nullable then adding the relationships and removing the nullable would fix it. So:
$table->unsignedBigInteger('module_id')->nullable();

Laravel General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")

Trying to migrate in laravel and this error poped up. I thought error could be bigInteger type as i found in another same question answer. Refer to change bigInteger to bigIncrements, but nothing i got another error about type constraint.
Code
public function up()
{
Schema::create('categories_products', function (Blueprint $table) {
$table->bigInteger('category_id')->unsigned()->index();
$table->bigInteger('product_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
}
Error
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `categori
es_products` add constraint `categories_products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) on delete cascade)
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")
Thanks.
It's hard to give a definate answer without seeing the column definition on the target table for the relation. The types need to match. So if you are using a bigIncrements() for the id field then unsignedBigInteger() or bigInteger()->unsigned() should both work as the type of the foreign key, however if you are using increments for the id then the foreign key needs to be an unsignedInteger() or integer()->unsigned()

How to fox laravel migration error "General error: 1005 Can't create table"

When I try to run migrations to create foreign key constraints I get the following error in my command prompt. I need help to overcome it as i searched a lot on the internet and tried many previous answers of same type question, unfortunately, none has worked
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table db_blog.category_posts (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table category_posts add constraint category_posts_post_id_foreign foreign key (post_id) references posts (id) on delete cascade) at
1
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table db_blog.category_posts (errno: 150 "Foreign key constraint is incorrectly formed")")
Please use the argument -v to see more details.
public function up()
{
Schema::create('category_posts', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->index();
$table->integer('category_id')->unsigned()->index();
$table->foreign('post_id')->references('id')->on('posts')-
>onDelete('cascade');
$table->timestamps();
});
}
I do not understand where there is a problem in this area
I do not know which version of your project, but in the latest ones, bigInteger is used in the foreign key, and for the ID, bigIncrements is used.
I also believe that the post table is being created first rather than the category_posts. Otherwise, have it first created.
Can you confirm if this would be it?

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

Laravel migration. I cannot add two foreign key referenced to same table

Schema::create('groups', function (Blueprint $table) {
$table->integer('year');
$table->integer('groups_number');
$table->primary(['year','groups_number']);
});
Schema::create('student_groups', function (Blueprint $table) {
$table->integer('student_groups_year');
$table->integer('student_groups_number');
$table->primary(['student_groups_year', 'student_groups_number']);
});
Schema::table('student_groups', function (Blueprint $table) {
$table->foreign('student_groups_year')
->references('year')->on('groups');
$table->foreign('student_groups_number')
->references('groups_number')->on('groups');
});
These are two diffrent files. I make the table in one file and the foreign keys in the other. The problem is when I make the second foreign key. When I only make one foreign key it works just fine, but when I make the second it get error. Anyway know why I can't make two foreign keys referenced to the same table? This is the error message I get.
In Connection.php line 664:
SQLSTATE[HY000]: General error: 1005 Can't create table bpo.#sql-26ec_995 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table student_groups add constraint student_grou
ps_student_groups_number_foreign foreign key (student_groups_number) references groups (groups_number))
In Connection.php line 458:
SQLSTATE[HY000]: General error: 1005 Can't create table bpo.#sql-26ec_995 (errno: 150 "Foreign key constraint is incorrectly formed")
I found the answer!! Couldn't find this anywhere and it was so simple! You have to put it in same foreign key code.
$table->foreign(['student_groups_number','student_groups_year'])
->references(['group_number','year'])->on('groups');
I found the answer!! Couldn't find this anywhere and it was so simple! You have to put it in same foreign key code.
$table->foreign(['student_groups_number','student_groups_year'])
->references(['group_number','year'])->on('groups');
change your foreign keys to an unsigned integer you can do this like
$table->integer('student_groups_number')->unsigned();
and make sure dont use varchar type as foreign key.
$table->integer('student_groups_year')->unsigned();
$table->integer('student_groups_number')->unsigned();
Hope this helps.

Categories