Reading Fields From Self-Referenced Table

I have a category table with a self-referencing parent field. All works ok, but I need to get id values of a particular record plus several levels of its parents. I’ve tried a lot different methods - neither works. Here is the code:




     $data = Category::model()->with

      (

        array('parent' => array('together' => true),

              'parent.parent' => array('alias' => 'grand_parent', 'together' => true),

              'parent.parent.parent' => array('alias' => 'grand_grand_parent', 'together' => true)

             )

      )->together()->findAll('t.id=:cat_id', array(':cat_id' => (int) $_POST['category_id']));



According to logs, this produces proper SQL statement, which, if executed manually, gives records with required fields. Nevertheless, the $data array contains ActiveRecord only with attributes of a single level, that is it contains fields only from Category, but no one field from Category.parent, Category.grand_parent, etc. If I add ‘select’ => ‘id’ into any of elements in the with clause, this exact element is somehow excluded from resulting SQL statement. For example, if I add ‘select’ => ‘id’ into the array for ‘parent’, the corresponding JOIN is removed from resulting SQL.

So, the question is: how to enforce the fields ‘id’, ‘parent.id’, ‘grand_parent.id’, etc from such a query with self-joined table to be placed in the $data’s attributes? Currently $data’s attributes are ‘id’, ‘name’, and other immediate fields only.

‘parent’ is defined in relations of Category as follows:


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



Thanks in advance.

Found it. :wink: It looks like I stuck in relational model, while it works in OO style.

The attributes of the parent are accessible via $data[0]->parent->attributes.

Hi can you help me to solve the same?

Thanks in Advanced.

My Post