<?php
class ChildidBehavior extends CActiveRecordBehavior
{
    public function afterDelete($event)
    {
        $this->updateChildId();
        
        return true;
    }
    
    public function afterSave($event)
    {
        $this->updateChildId();
        
        return true;
    }
    private function updateChildId()
    {
        $childfid = $havechild = $updatefids = array();
        $forums = $this->Owner->findAll("childid=1");
        if (!empty($forums))
        {
            foreach ($forums as $forum)
            {
                $childfid[] = $forum->fid;
            }
        }
        $criteria = new CDbCriteria();
        $criteria->select = 'fid,fup';
        $criteria->order = 'type';
        $forums = $this->Owner->findAll($criteria);
        if (!empty($forums))
        {
            foreach ($forums as $forum)
            {
                $forum->fup > 0 && $havechild[$forum->fup] = 1;
            }
        }
        $havechild = array_keys($havechild);
	    $fids = array_diff($childfid,$havechild);
	    //print_r($fids);die;
	    if ($fids)
	    {
	        $criteria = new CDbCriteria();
	        $criteria->addInCondition('fid', $fids);
	        $forums = $this->Owner->findAll($criteria);
	        foreach ($forums as $forum)
	        {
	            $forum->childid = 0;
	            $forum->save();
	        }
	    }
	    
	    $fids = array_diff($havechild,$childfid);
	    if ($fids)
	    {
	        $criteria = new CDbCriteria();
	        $criteria->addInCondition('fid', $fids);
	        $forums = $this->Owner->findAll($criteria);
	        foreach ($forums as $forum)
	        {
	            $forum->childid = 1;
	            $forum->save();
	        }
	    }
    }
}