I've got a self referencing table in my db and would like to pull it as an object using Phalcon ORM. The hasOne() relationship works when joining to other tables but doesnt seem to work when trying to reference itself. When trying to var_dump($treeNode->TreeNodes)
it returns nothing. Inspecting the object just returns 'Cannot evaluate expression' using XDebug.
Does anyone know how to do this in Phalcon?
public function organisationAction()
{
$organisation = new Organisations();
$organisation->setConnectionService(Registry::setConnection(Connections::UK_Connection));
$organisation = $organisation->findFirst(123);
$treeNodes = $organisation->TreeNodes;
foreach($treeNodes as $treeNode){
var_dump($treeNode->TreeNodes);
}
}
class TreeNodes extends Model
{
public $node_id;
public $tree_id;
public $tree_parent_node_id;
public $tree_level_id;
public $node_desc;
public function getSource()
{
return "TreeNodes";
}
public function initialize()
{
$this->setSource("TreeNodes");
$this->hasOne(
'tree_parent_node_id',
'TreeNodes',
'node_id',
array(
'reusable' => true
)
);
}
}
An easy way to achieve this is by defining an additional relationship
$this->belongsTo('tree_parent_node_id', // which column
'TreeNodes', // referenced table
'id', // referenced table column
['alias' => 'parentNode']);
To avoid confusion you can give this relation an alias. ['alias' => 'parentNode']
Now you should be able to access the related parent node by using
$treeNode->getRelated('parentNode');
More information about Phalcon aliases.