7.4. Reassigning Products from Deleted Categories
Now that you've met with Claudia, you know how she wants to handle potentially orphaned products. Orphaned products come about as a natural result of deleting a "container" like a category. If the category goes away, what do you do with all the items that it is "holding"? Now that you know what Claudia's expectations are, it's an easy matter of adding a bit of processing to the end of the admin/categories/delete function.
Here's a quick look at that function to refresh your memory:
function delete($id){ $this->MCats->deleteCategory($id); $this->session->set_flashdata('message','Category deleted'); redirect('admin/categories/index','refresh'); }
What you're going to need when you rewrite this function is some way to check for orphaned products. The best way to do that is to create a checkOrphans() function in the MCats model. This function accepts a category ID as its only argument and then returns an array of products that match that category_id.
function checkOrphans($id){ $data = array(); $this->db->select('id,name'); $this->db->where('category_id',$id); $Q = $this->db->get('products'); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[$row['id']] = $row['name']; } } $Q->free_result(); return $data; }
Now that you have this function in place, you can rewrite the delete() controller function.
function delete($id){ $this->MCats->deleteCategory($id); $orphans = $this->MCats->checkOrphans($id); if (count($orphans)){ ...
Get Professional CodeIgniter® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.