I have this MySql database table:
tbl_project
id
project_name
parent_id
If a project is a 'parent', parent_id is 0.
Now I'm trying to add a self referencing foreign key
CONSTRAINT `FK_tbl_project_tbl_project` FOREIGN KEY (`parent_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE
When I try to insert a new record,
SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (mydbname.#sql-3539_d7d, CONSTRAINT FK_tbl_project_tbl_project FOREIGN KEY (parent_id) REFERENCES tbl_project (id) ON DELETE CASCADE)
Basically I just want all the children to be deleted when I delete the parent. What am I missing here?
When you enter any value into the parent_id column of a new row, the foreign key requires that there is a row where id has that value, because that's how foreign keys work.
If you want to use a foreign key with your self-referencing relationship, you should use NULL instead of 0 for the parent_id of a row that has no parent to reference. Foreign keys ignore NULL.
Related
I had already created the database and all tables with foreign key constraints, but I had a column in parent table which was unique and was part of composite key, so I had to drop all foreign key constraints from all child tables and then dropped the unique constraint on parent table.
Now when I am adding foreign key constraint back to all child tables, it gives error: foreign key constraint is incorrectly formed, although I have checked both my parent and child table columns and they are of same type using same engine, unicode and all. But still this is thrown.
When I checked the table structure of child table, it has an index defined for the foreign key and the column is child column foreign key, so I tried after removing it but still error.
Query
ALTER TABLE `child_table` ADD CONSTRAINT FOREIGN KEY `fk_parent_table_child_table_column_name` (child_table_column_name)
REFERENCES `parent_table`(parent_table_column_name) ON DELETE RESTRICT ON UPDATE NO ACTION;
both columns are VARCHAR PRIMARY KEY and NOT NULL
If more information is required please ask.
EDIT
So far I have tried to dropped the index, dropped the PRIMARY KEY CONSTRAINT from child table and dropping the column then adding it back with VARCHAR(14), NOT NULL, still no success.
EDIT 2
Also tried to add the child column in primary key and then tried to apply foreign key constraint, no success so far.
Since no one answered and I couldn't find a solution to my problem I had to drop the child foreign keys and then remove the parent composite key so as to remove the parent column which was VARCHAR(14) and then again create foreign keys with new primary key.
I have a foreign relationship with category_id column in database but while deleting i get error.
This is my code for delete:
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
Session::flash('success', 'The category was successfully deleted.');
return redirect()->route('categories.index');
}
Error i seen is :
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`fitilicious`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 2)
Please help.
My bet is on the foreign key being set to ON DELETE RESTRICT instead of CASCADE.
Cannot delete or update a parent row: a foreign key constraint fails (fitilicious.products, CONSTRAINT products_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id)) (SQL: delete from categories where id = 2)
This tells us that there is a row in table "products" which is referencing the category you are attempting to delete.
ON DELETE CASCADE will also delete the product.
ON DELETE RESTRICT will prevent deletion of a non-empty category
ON DELETE SET NULL will delete the category and set category_id to NULL in products table
Each has its uses, but you need to choose which one you need.
so i am trying again and again to make a column as a foreign key but it gives me Constraint name error? what Constraint name should i put? i am using PHPmyadmin SQL , I tried giving it names such as trackid and so on but still i am getting an error
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
MySQL said: Documentation
1452 - Cannot add or update a child row: a foreign key constraint fails (projectdatabase.
'#sql-1414_6c7'>, CONSTRAINT track_id FOREIGN KEY (track_id) REF
ERENCES ss_orders (track_id) ON UPDATE CASCADE)
If you have data in child table for the referred column field, to add foreign key on that field,
first you have to disable foreign key checking.
And then alter to add foreign key.
And lastly reset the constraint checking.
Step 1: Disable the foreign key checks.
set foreign_key_checks=0;
Step 2: Now add the foreign key constraint.
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
Step 3: Now reset the foreign key checks.
set foreign_key_checks=1;
It is possible that you have table ss_ordered_carts filled with wrong data, that cannot be related. Check it using this query -
SELECT * FROM ss_ordered_carts t1
LEFT JOIN ss_orders t2
ON t1.track_id = t2.track_id
WHERE
t2.track_id IS NULL;
Then modify table's data, and after, create foreign key.
Try this.
mysql> SET foreign_key_checks = 0;
mysql> ALTER TABLE ss_ordered_carts
ADD CONSTRAINT track_id
FOREIGN KEY(track_id)
REFERENCES ss_orders(track_id)
mysql> SET foreign_key_checks = 1;
May be, you are getting the specified error as there exists data in the tables.
This may also occur if child table contain some data with the foreign key that that are not in parent table. In this case try,
Delete from child where child_id NOT IN (select parent_id from parent where parent.id = child.id)
I needed an example of cascade delete. My question is, where do I add it? In the table I create PK, or in other tables where this PK is sitting there as FK?
Can I use "alter table" to add "on delete cascade" to existing table? An example please?
#edit
MYSQL, using phpMyAdmin
#edit 2
Does it look good?
alter table wplaty
drop foreign key pesel,
add constraint pesel foreign key (pesel)
references baza_osob(pesel) on delete cascade on update restrict;
My parent table = baza_osob
My child table = wplaty
PK is pesel, FK is pesel as well.
#edit3
Got error:
#1025 - Error on rename of '.\projekt\wplaty' to '.\projekt#sql2-1300-6c' (errno: 152)
cascade directives go into the "child" tables, e.g.
create table parent (
id int primary key
)
create table child (
id int primary key
parent_id int,
foreign key (parent_id) references parent (id)
on delete cascade
)
Never tried doing an alter on a foreign key to change its on settings, but worst case, you simply drop the existing FK and redefine it with the new on settings in place.
You actually don't add the 'ON DELETE CASCADE' on a table. It's part (or not) of each Foreign Key definition.
You need to enable this option for the foreign key. If you did not add this option when you created foreign key, then you should recreate it.
alter table <table> drop foreign key <fk name>;
alter table <table> add constraint <fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;
In one statement:
alter table <table>
drop foreign key <old fk name>,
add constraint <new fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;
That is the primary table field (tasks table):
task_id int(10) UNSIGNED No None AUTO_INCREMENT
This is my foreign table field (url_error_stats table):
task_id int(10) UNSIGNED No None
url_error_stats doesnt present the "relation view" option to connect between the keys..why?
SQL query:
ALTER TABLE url_error_stats ADD FOREIGN KEY ( task_id )
REFERENCES aws_backlinks.tasks (
task_id ) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL said:
1452 - Cannot add or update a child row: a foreign key constraint
fails (aws_backlinks., CONSTRAINT #sql-6f0_3bd_ibfk_1 FOREIGN KEY
(task_id) REFERENCES tasks (task_id) ON DELETE CASCADE ON UPDATE
CASCADE)
you have to use innodb and index the primary key if you want to create the foreign keys. and I will recommend you to use NAVICAT . its much easier to create foreign keys and quick too. but for a quick phpmyadmin guide see
Setting up foreign keys in phpMyAdmin?
Another reason can be the unrelated data in your tables. I mean you may have a foreign key that doesn't exist in parent table.
in this , click on url_error_stats table, then on right hand side it will show all the fields list, so now check on checkbox of that particular field which u wanted to be foreign and click on the link relation view (which is provided by phpmyadmin below to the table fields with blue color hyperlink).
it will open relationship screen , there You can select the field of the primary table.
Thanks