Seeding Laravel many to many table with data - php

I have 3 tables; orders, products and order_product. I am trying to seed the order_product pivot table using the Seeder class.
This is what I have in my code;
$productArray = \Illuminate\Support\Facades\DB::table('products')->pluck('id')->toArray();
factory(App\Order::class, 60)->create()->each(function ($order) use ($productArray) {
$randomPickings = mt_rand(1, 4);
$order->products()->sync(array_rand($productArray, $randomPickings));
});
I want attach product ids from the $productArray so an order can have, say, 1,2,3,4 or 5 products attached after seeding. Currently, I get this error when I run the seeder.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(`foo`.`order_product`, CONSTRAINT
`order_product_product_id_foreign` FOREIGN KEY (`product_id`)
REFERENCES `products` (`id`) ON DELETE CASCADE) (SQL: insert into
`order_product` (`order_id`, `product_id`) values (2, 0))
There's no product with id 0. I'm guessing it's picking the indexes instead of the values. How do I get the values selected/picked instead? Thanks.

Related

Laravel SQLSTATE[23000]: Integrity constraint violation: 1452

I am facing an integrity constraints issue when adding a new row to a table has relation with another table (children and visits tables) every child has many visits.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (vaccine.visits, CONSTRAINT visits_ch_id_foreign FOREIGN KEY (ch_id) REFERENCES childern (id)) (SQL: insert into visits (ch_id, ce_id, emp_id, next_visit, notes, updated_at, created_at) values (202151-15, 1, 2, 2021-05-21, this is a test, 2021-05-17 07:30:48, 2021-05-17 07:30:48))
I am understanding the error message that should the value in the foreign key (ch_id) in the visits table should be found in the primary key (id) in the children key.
The problem is the value already exists in the primary table but I am getting the same error
Here is my code and screenshot for the database
$visit=new Visit();
$visit->ch_id=$child_id;
$visit->ce_id=1;
$visit->emp_id=2;
$visit->next_visit=$request->input('next_visit_date');
$visit->notes=$request->input('visit_notes');
$result=$visit->save();
I am testing on value 202151-15 and it already exists on the children table as following:

Laravel CRUD delete not working on foreign 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.

PHP PDO - Inserting into table with foreign keys

I want to insert into a table called Festivals that has two foreign keys (venueID & ticketID).
The SQL:
$addFestivalSql = "INSERT INTO festivals
VALUES(DEFAULT, :festivalName, :festivalDescription,
:festivalImage, :festivalLineup,
:musicTypeId, DEFAULT, DEFAULT)";
The error:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
The Festivals Table:
The Festivals Table
I've created the two foreign key constraints with venueID and ticketID relating to the two primary keys.
Why do you think I'm getting this error?
Thanks.

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.

Categories