mysql SQLSTATE[23000] error on laravel - php

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.

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();
});

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();

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 cannot add foreign key constraint

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.

Laravel-OCI8 ORA-02275: such a referential constraint already exists in the table

I've been trying to use migrations for a cross-dbms database. Using entrust and confide packages, I added migrations after them to add a user_statuses table and a reference in users table to user-statuses' ids; but as I define the foreign key I get this:
[Illuminate\Database\QueryException]
Error Code : 2275
Error Message : ORA-02275: such a referential constraint already exists in the table
Position : 53
Statement : alter table users add constraint users_state_foreign foreign key ( state ) references user_statuses ( id ) (SQL: alter table users add constraint users_state_foreign foreign key ( state ) references user_statuses ( id ))
[yajra\Pdo\Oci8\Exceptions\SqlException]
Error Code : 2275
Error Message : ORA-02275: such a referential constraint already exists in the table
Position : 53
Statement : alter table users add constraint users_state_foreign foreign key ( state ) peferences user_statuses ( id )
Below are the user_statuses and the alteration migration.
user_status creation:
Schema::create('user_statuses', function($table){
// Columns
$table->increments('id')->unsigned();
$table->string('name');
// Indexes
// Constraints
});
users alteration:
Schema::table('users',function($table){
// Columns
$table->integer('state')->unsigned();
$table->softDeletes();
// Indexed
// Constraints
$table->foreign('state')->references('id')->on('user_statuses');
});
This is already fix at version https://github.com/yajra/laravel-oci8/tree/v1.5.11
Please try or submit an issue to our repo.
I put the foreign() statement in another, new Schema::table() statement in the same file, just bellow the one that creates columns as bellow:
Schema::table('users', function($table){
// Columns
$table->integer('kojak')->unsigned();
$table->softDeletes();
// Indexed
// Constraints
});
Schema::table('users', function($table){
$table->foreign('kojak')->references('id')->on('user_statuses');
});
This solved my problem, but the question remains why the conventional code doesn't work.

Categories