如何正确实现此Yii / PHP / SQL代码

public function actionView($id)
{
    $criteria = new CDbCriteria();

    $cat = ECCategory::model()->findAll();

    foreach ($cat as $cats) {
        if ($cats->ParentID == $id) {
            $criteria->condition = 't.ParentID=' . $id; // that is if there are more category inside category show them
        } else { // else display the products belonging to that category
            $criteria->join = 'RIGHT JOIN ECProduct AS b ON t.ID = b.CategoryID';
            $criteria->condition = 't.ID=' . $id;
        }
    }

    $dataProvider = new CActiveDataProvider('ECCategory', array(
        'criteria' => $criteria
    ));

    $this->render(
        'view', array(
            'model' => $this->loadModel($id), 'dataProvider' => $dataProvider,
        )
    );
}

This doesn't work as I hoped. It ignores the IF statement and jumps to the else producing latter results. How can I write this condition, is there a different way I can do this. The data pulled will depend on the condition, one or the other condition will be met. Now it the IF statement has no effect, unless I remove the else part the first part is never reached.

Thanks