Hierarchical Models

Hi! It’s my beginning with AR and Yii. My ‘user’ table has such structure:




CREATE TABLE `user` (

	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,

	`uid` VARCHAR(16) NOT NULL,

	...

	`superior_uid` VARCHAR(16) NULL DEFAULT NULL,

	...

	UNIQUE INDEX `uid` (`uid`),

	...

	CONSTRAINT `FK_user_user` FOREIGN KEY (`superior_uid`) REFERENCES `user` (`uid`) ON UPDATE CASCADE ON DELETE SET NULL,

)



relations in model:




            'superior' => array(self::BELONGS_TO, 'User', 'superior_uid'),

            'subordinates' => array(self::HAS_MANY, 'User', 'superior_uid'),



I’ve been sarching many forums for a few days and didn’t find statisfied solution. I need to do two things:

  1. Find all children for UID and it’s relation level.

  2. Compare two UIDs and check if they have parent<->children relation (on any level, not just straight).

Can you help, please?

Hi Dominik, welcome to Yii.

You have a classic Tree table.

There are several extensions/behaviors out there working with trees, but I could find only one extension/behavior that "reads parents and children records via relations" (which is what you want to do).

Check out XTreeBehavior in Yii-Playground and on GitHub.