phpmysqlcodeignitercascading-deletes

How to delete sub categories in codeigniter


How to delete all sub categories and their inner categories if I delete the main category ?

Table

Here if I delete the category 'computer' means how to delete their sub categories also (mouse,keyboard,virtual,touch) ?


Solution

  • You have one of the following options to accomplish this:

    1- You setup your database to enforce referential integrity, then it's as easy as telling MySQL ON DELETE CASCADE;

    Note tested, but I guess it should work.

    ALTER TABLE categories
    ADD FOREIGN KEY (parent_id)
    REFERENCES Categories(id)
    ON DELETE CASCADE;
    

    2- Second option is calling your delete function recursively to accomplish this. example:

    public function delete_category_by_id ($category_id) {
        // delete this category.
        $this->db->delete('categories', ['id' => $category_id]);
        // fetch child categories & call the same method again.
        $q = $this->db->where('parent_id', $category_id)->get('categories');
        foreach( $q->result() as $Child ) {
            $this->delete_category_by_id($Child->id);
        }
    }
    

    This would be very destructive & it might take long time depending on how many levels you have