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();
Related
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();
});
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
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.
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".
I am using laravel schema builder and here is my code...
//create links table
Schema::create('links', function($table){
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('domain_id');
$table->string('url');
$table->softDeletes();
$table->timestamps();
});
Schema::table('links', function($table) {
$table->index('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->index('domain_id');
$table->foreign('domain_id')->references('id')->on('domains')->onDelete('cascade')->onUpdate('cascade');
});
}
But i try to save something to this table it throws following error...
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`we`.`links`, CONSTRAINT `links_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `links` (`updated_at`, `created_at`) values (2014-09-04 17:35:53, 2014-09-04 17:35:53))
Please suggest if you need anything more to understand this better, help me to fix this.
thanks
If the SQL statement's to be believed somewhere the app's inserting just the timestamps fields (updated_at, created_at). You need to at least specify an existing user_id for the query. If there are cases where you can insert into links without associating a user, you need to update the links table so links.user_id allows for null values. You can't update a column on an existing table to accept nulls through the schema manager, you'll need to do that through a manual query.