Temat: deleteThreaded
Szukalem jakiegos zgrabnego rozwiazania (byc moze nie dokladnie i wynalazlem kolo poraz drugi) na usuwanie rekordow z drzewka opartego tylko o parent_id... (bez wag left i right) i splodzilem takich kilka metod modelu :
/**
* Deletes tree element with all of his descendants.
* @return boolean
* @param array $records Results of find("threaded") query.
* @param array $recordToDelete id of record to be deleted.
* @param mixed $model Instance of model or null. When null this object will be used.
*/
public function deleteAllThreaded($records,$recordToDelete,$model =null)
{
$flatArray = array();
if(is_null($model))
{
$model = $this;
}
$this->toSingleDimmension($flatArray, $records,$model->name);
$toDelete[] = $recordToDelete;
$this->findChildren($toDelete,$flatArray,$recordToDelete);
$model->deleteAll(array("id" => $toDelete));
return true;
}
/**
* Makes multidimensional array falt.
* Recurrent helper method.
* @param array $flatArray Destination array.
* @param array $data Multidimensional array.
* @param string $model Model name.
*/
private function toSingleDimmension(&$flatArray, $data, $modelName)
{
foreach($data as $record)
{
$flatArray[] = $record[$modelName];
if(!empty($record["children"]))
{
$this->toSingleDimmension($flatArray, $record["children"],$modelName);
}
}
}
/**
* Searches all given records to the bottom, for children with given $parentId
* Recurrent helper method.
* @param array $toDelete stack for ids of record to be deleted.
* @param array $records falt array which contains flat array created from results of find("threaded").
* @param integer $parentId id of parent to search for.
*/
private function findChildren(&$toDelete,$records,$parentId)
{
foreach($records as $record)
{
if($record["parent_id"] == $parentId)
{
$toDelete[] = $record["id"];
$this->findChildren($toDelete,$records,$record["id"]);
}
}
}Wsie metody powinny sie znadywac w modelu lub w app model.
pryklad uzycia ....
public function deleteTreeElement($data)
{
$TemplateMenuItem = $this->getModelObject("TemplateMenuItem");
$records = $TemplateMenuItem->find("threaded");
$this->deleteAllThreaded($records,$data["elementId"], $TemplateMenuItem);
....
}Ostatnio edytowany przez robal77 (2009-08-05 12:54:03)