We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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


98.9k
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;