Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Parent Relationship In Same Model

Hi I have asked for related question but I want to clear that Phalcon has many great libraries/features about most common problems. But in detail, things are should done by developers. For example I want to get simple recursive category pattern in same model. For this I must write my recursive pattern Phalcon ORM not give me this stuation.

<?php

 class Category extends Phalcon\Mvc\Model {


        public function childCategory()
        {
            return $this->belongsTo('parent_id', 'Category');
        }

    }

Category::with('childCategory')->find(); // can give me all recursive category structure, no need foreach every item recursively


82.3k
Accepted
answer
edited Oct '14

Define the relation this way:

class Category extends Phalcon\Mvc\Model
{
    public $id;
    public $parent_id;
    public $name;

    public function initialize()
    {
        $this->belongsTo('parent_id', 'Category', 'id', ['alias' => 'parent']);
    }
}

Usage:

$category = Category::findFirst();
$category->parent;