How to define relational rules for parent/child hierarchy

I wondering how to define relational rules for a model that points to itself through an associative table. The purpose of the associative table is to define a hierarchy of parent/child relationships.

Following is an example of the tables I am working with:

This is the "group" table:


CREATE TABLE `tbl_group` (

  `id` int(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NOT NULL AUTO_INCREMENT,

  `name` varchar(100) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 

This is the associative table that defines the parent/child hierarchy:


CREATE TABLE `tbl_group_child` (

  `parent` int(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NOT NULL,

  `child` int(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NOT NULL,

  KEY `FK_group_child_parent_constraint` (`parent`),

  KEY `FK_group_child_child_constraint` (`child`),

  CONSTRAINT `FK_group_child_child_constraint` FOREIGN KEY (`child`) REFERENCES `tbl_group` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,

  CONSTRAINT `FK_group_child_parent_constraint` FOREIGN KEY (`parent`) REFERENCES `tbl_group` (`id`) ON DELETE CASCADE ON UPDATE CASCADE

) ENGINE=InnoDB DEFAULT CHARSET=latin1

Here are the relational rules I have defined for the tbl_group model. (Yii is not happy with this.)




	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

            'child' => array(self::MANY_MANY, 'Group', 'tbl_group_child(parent, child)'),

            'parent' => array(self::MANY_MANY, 'Group', 'tbl_group_child(child, parent)'),

        );

	}

How should I define the relational rules in the model for tbl_group?

would this work? or I missed any of your points?




CREATE TABLE `tbl_group` (

  `id` int(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NOT NULL AUTO_INCREMENT,

  `parent_id` int(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NULL,

  `name` varchar(100) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 



for top group’s parent_id would be Null




	public function relations()

	{

	     return array(

            'children' => array(self::HAS_MANY, 'Group', 'parent_id'),

            'parent' => array(self::BELONGS_TO, 'Group', 'parent_id'),

        );

	}

Through self should help you to achieve your task

It turns out that the relational rules I defined above are correct. I made a mistake elsewhere in the code.