Laravel CRUD delete not working on foreign key - php

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.

Related

MySQL cascade delete on self-referencing parent-child table?

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.

MYSQL and PHP: How to add mysql constraint but proceed anyway if not found

I have a code where I need a foreign key check disabled when updating. But I still need it to check for the foreign key but proceed anyways if the key is not found. The installation keeps breaking due to this.
$installthis->run("
ALTER TABLE `{$this->getTable('sweets/results')}`
ADD CONSTRAINT `FK_SWEETS_RESULTS_SWEET_ID_SWEETS_ID` FOREIGN KEY (`sweet_id`)
REFERENCES `{$this->getTable('sweets/sweets')}` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE `{$this->getTable('sweets/results_values')}`
ADD CONSTRAINT `FK_SWEETS_RESULTS_VALUES_RESULT_ID_SWEETS_RESULTS_ID` FOREIGN KEY (`result_id`)
REFERENCES `{$this->getTable('sweets/results')}` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
");
What do I need to change or add if I want it to proceed?
Edit:
The error states that
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(sweets_database.sweets_results, CONSTRAINT
FK_SWEETS_RESULTS_SWEET_ID_SWEETS_ID FOREIGN KEY (sweet_id)
REFERENCES sweets (id) ON DELETE CASCADE ON UPDATE CASCADE), query
was: INSERT INTO sweets_results (customer_id, created_time,
update_time) VALUES (?, '2018-11-02 05:35:24', '2018-11-02
05:35:24')

Mysql foreign key

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)

when I click delete it will display this error?

Here is the sql error
SQL error: Cannot delete or update a parent row: a foreign key constraint fails (`motioncenter`.`news`, CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`) REFERENCES `categories` (`category_id`))
Line: 36
Fil: C:\Xampp\htdocs\xampp\site\admin\page_functions\category_delete.php
herre is the category_delete.php file
Line: 36 is echo format_error_message(mysqli_error($database_link), $query, LINE, FILE);
<?php
if ( !isset($database_link))
{
die(header('location: index.php?page=categories'));
}
if ( !isset($_GET['category_id']))
{
die(header('location: index.php?page=categories'));
}
$category_id = ($_GET['category_id'] * 1);
$query = "DELETE FROM categories WHERE category_id = $category_id";
if (mysqli_query($database_link, $query))
{
$_SESSION['message'] .= 'deleted<br />';
die(header('location: index.php?page=categories'));
}
else
{
echo format_error_message(mysqli_error($database_link), $query, __LINE__, __FILE__);
}
?>
Probably your constraint that links items to category prevents you from deleting a category, while some items, news in your example, are still referencing it. Perhaps you should modify your foreign key constraint so that it does cascade delete, like ON DELETE CASCADE
Your database contains foreign keys that have been configured such that you cannot delete categories if there are any news items in that category.
It's kind of like trying to rm a directory that has files in it, you'll get an error saying the directory is not empty.
Add a query to "DELETE FROM news WHERE category_id=".$category_id or update the news items to be in a different category before deleting the category itself.
Deleting a category_id from the category table leads to an error since category_id acts a foreign key in another table. By deleting a value in category_id, all the other instances of that value in other table that reference it will be invalid.
You need to first delete tables with a foreign key referenced to your categories table.
motioncenter.news table has fk_categories_id field with the value you are trying to delete. you need to either delete that row in news table first or use below sql statement to disable foreign checks alltogether.
SET FOREIGN_KEY_CHECKS=0;
First you've to delete all news which is dependent on that category.
Then you can delete that category.
Or alternatively you can change constraint for foreign key:
# Table `motioncenter`.`news`
ALTER TABLE `motioncenter`.`news`
DROP FOREIGN KEY `news_ibfk_2`,
ADD CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`)
REFERENCES `categories` (`category_id`) ON DELETE CASCADE
Or if you want to keep all related news even then you should change to:
# Table `motioncenter`.`news`
ALTER TABLE `motioncenter`.`news`
DROP FOREIGN KEY `news_ibfk_2`,
ADD CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`)
REFERENCES `categories` (`category_id`) ON DELETE SET NULL
Because by default foreign key prevent deletion of parent record.

MySQL cannot INSERT with FK constraint

I get the following error message when I try to INSERT some data:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(database/UserDetails, CONSTRAINT UserDetails_ibfk_6 FOREIGN
KEY (HearAboutID) REFERENCES UserDetails (HearAboutID) ON DELETE
CASCADE ON UPDATE CASCADE)
The FK relationship looks like this:
The data I'm trying to enter into UserDetails.HearAboutID is present in UserHearAbout.UserHearAboutID... so why won't it go? :(
From the error you posted
FOREIGN KEY (HearAboutID) REFERENCES UserDetails (HearAboutID) ON DELETE CASCADE ON UPDATE CASCADE)
(you actually created a constraint that refers to the same table and same column),
I guess that your FK constraint definition is wrong (it should be
FOREIGN KEY (HearAboutID) REFERENCES UserHearAbout (UserHearAboutID)
ON DELETE CASCADE ON UPDATE CASCADE)

Categories