Skip to content

Instantly share code, notes, and snippets.

@mehedithedue
Created August 15, 2018 19:29
Show Gist options
  • Save mehedithedue/848972173306ecd4d1d30c66ff52d339 to your computer and use it in GitHub Desktop.
Save mehedithedue/848972173306ecd4d1d30c66ff52d339 to your computer and use it in GitHub Desktop.
mysql> select * from product_category;
+-----------+----------------+---------------------+
| id | category_id | product_id |
+-----------+----------------+---------------------+
| 1 | 1 | 2 |
| 2 | 2 | 2 |
| 3 | 3 | 2 |
| 4 | 2 | 3 |
| 5 | 2 | 4 |
| 6 | 3 | 4
+-----------+----------------+---------------------+
When edit a single product the coresponsing category have to edited. The Easy way is to delete all the row which match the
poduct_id then insert but its not effecient.
To Solve the problem have to figure out the new item in edit form that must be inserted in database.
and the removed item from the input form that also must be deleted from datbaso.
if we get the collection of two array, one array is existing category_id for this product.
another array is the category id inpute from html form (by multiple select or checkbox whatever)
if we use array_diff() two array in both order, we get the item we have to delete and item we have to insert.
The array element which is unchanged is not comes in these array_diff(). so no need to take action on them.
--------------------------------------------------------------------------------------------------------------------------
$removedCategoryItem = array_diff($existingCategoryInDB, $categoryFromInput);
$addedCategoryItem = array_diff($categoryFromInput, $existingCategoryInDB);
ProductCategoryTable::remove( where('product_id' = $id) and where_in('category_id' = $removedCategoryItem) );
ProductCategoryTable::insert([
(foreach loop-> $addedCategoryItem as $categoryItem){
'category_id' => $categoryItem ,
'product_id' => $id,
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment