Search code examples
phpactiverecordphpactiverecord

How to self reference in PHP ActiveRecord


I have a table "categories". Each category could have a parent category.

 Categories
    id 
    parent_category
    title

There is only one parent_category for each category

My questions are :

  1. What is the code for the Category model?
  2. Given a category '$category' what do I type to output the parent category title?

Solution

  • You might try the following...

    <?php
    
    class Category extends ActiveRecord\Model {
       static $belongs_to = array(
            array('parent', 'foreign_key' => 'parent_category', 'class_name' => 'Category')
       );
    
       static $has_many = array(
            array('children', 'foreign_key' => 'parent_category', 'class_name' => 'Category'),
        );
    
    }
    

    You can simply retrieve the parent category:

    $category = Category::find(1); 
    print 'Parent Title : ' . $category->parent->title;
    

    Or retrive all children categories:

    $categoryParent = Category::find(1);
    // loop through all child elements...
    foreach ($categoryParent->children as $category)  {
        print $category->title . ' <br/>';
    }