Use Of Empty Parent_Id

Hi,

I’ve got a db table with all categories and subcategories. They are connected with a column parent_id.

Some people say that using an empty value “” for the top level categories is better than using a zero “0” value. It’s true that this is handy when is comes to dropdown lists and you can use the empty option.

But now I got my admin page and I want to use draggable sorting. It’s too complex for me to build it in one page like this wiki suggests (http://www.yiiframework.com/wiki/323/dynamic-parent-and-child-cgridview-on-single-view-using-ajax-to-update-child-gridview-via-controller-after-row-in-parent-gridview-was-clicked).

So I thought to only show the main categories and when I click on one I show the child categories. So I can use the UI sortable function on that which works great.

But how to start with only the main categories, an empty parent_id just gives me all the categories.




	public function actionAdmin()

	{

		$model=new Category('search');

		$model->unsetAttributes();  // clear any default values		


		if(!isset($_GET['Category']['parent_id']))

			$model->attributes=array('parent_id'=>'');

		

		if(isset($_GET['Category']))

			$model->attributes=$_GET['Category'];

		

		$this->render('admin',array(

			'model'=>$model,

		));

	}



Technically, only existing and NULL values are allowed for foreign keys.

Ok, I’ve changed “” into NULL in the table.




		if(!isset($_GET['Category']['parent_id']))

			$model->attributes=array('parent_id'=>'NULL');

			

			// or like this, same result.

			$model->attributes=array('parent_id'=>new CDbExpression('NULL'));




Now gives me no results at all…

I’ve changed it into:





        // In actionAdmin:

	if(!isset($_GET['Category']['parent_id']))

		$model->mainCategories();


        // In the model:

        public function scopes()

        {

                return array(

                        'mainCategories'=>array(

                                'condition'=>'parent_id IS NULL',

                                'order'=>'ordering',

                        ),

                );

        }



That seemt to work correct. Not sure if this is the best solution though.