Welcome Guest, Not a member yet? Register   Sign In
DataMapper: Delete Dependant Objects
#1

[eluser]cberk[/eluser]
Below is a function I wrote to extend the DataMapper library. I needed to delete not only an object and its relationships, but also other objects that depended on this object, and still more objects that depended on these objects, etc. This function does the job nicely. See the comment below for more details.

Code:
// --------------------------------------------------------------------

/**
* Delete Dependants method (USE CAUTION IN CALLING THIS FUNCTION!)
*
* Deletes the dependant objects for a given parent object.  Does not delete
* the parent object itself.
*
* A "dependant" is defined as an object whose "has_one" array contains the
* parent object, AND where this relationship is required.  This should
* help insure that only the desired objects are deleted.
*
* BE VERY CAREFUL in calling this function, as it has the ability to destroy
* important data.  You must understand the relationships between objects
* to understand the consequences of calling this function.
*
* NOTE: You can exempt an object from being deleted by setting
* "var $delete_protect = TRUE" in your model. (Simply declaring this variable
* turns this setting on.)
*
* ALSO NOTE: This function calls itself recursively, so if you have very
* deep parent-dependant relationships, the process becomes intensive.    
*
* @access    public
* @return    void
*/

function delete_dependants()
{
    foreach ($this->all as $parent) // Loop through each of the parent objects, if there is more than one.
    {
        foreach($parent->has_many as $model)  // Check each of the parent object's $has_many relationships
        {
            $object = new $model;
            if (in_array($parent->model,$object->has_one) && !isset($object->delete_protect)) // Criterium 1: $has_one array contains parent object. (Delete Protection)
            {
                foreach ($object->validation as $field) // Loop through validation array
                {
                    if ($field['field'] == $parent->model && in_array('required',$field['rules'])) // Criterium 2: relationship is required
                    {
                        // Get dependant objects
                        $object->where_related($parent)->get();
                        
                        // RECURSION: Delete its dependants
                        $object->delete_dependants();
                        
                        // Delete All Objects
                        $object->delete_all();
                        //echo "Deleting " . count($object->all) . ' ' . $object->model . '<br />';
                    }
                }
            }
        }
    }
}




Theme © iAndrew 2016 - Forum software by © MyBB