I am currently working with a database that stores regions in a hierarchy based on the depth between the parent and the child.
Database
CREATE TABLE regions (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(100) NOT NULL,
`chain` TINYTEXT NOT NULL,
);
CREATE TABLE regions_tree (
`parent_id` INT NOT NULL,
`child_id` INT NOT NULL,
`depth` INT NOT NULL DEFAULT 0
);
Table: regions
id name chain
1 All All
2 Asia Pacific All-Asia Pacific
3 Australia All-Asia Pacific-Australia
4 Queensland All-Asia Pacific-Australia-Queensland
5 New South Wales All-Asia Pacific-Australia-New South Wales
Table: regions_tree
parent_id child_id depth
1 1 0
2 2 0
2 1 1
3 3 0
3 2 1
3 1 2
4 4 0
4 3 1
4 2 2
4 1 3
5 5 0
5 3 1
5 2 2
5 1 3
I am able to return a resultset of an individual region's parents by defining a hasManyToMany()
relationship in the Regions
model:
Models
class RegionsTree extends \Phalcon\Mvc\Model
{
public function getSource()
{
return 'regions_tree';
}
}
class Regions extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasManytoMany('id', 'RegionsTree', 'child_id', 'parent_id', 'Regions', 'id', array('alias' => 'parents'));
}
}
Controller
$this->view->regions = Regions::find();
View
{% for region in regions %}
<p>{{ region.name }} - {{ region.parents.getFirst().name }}</p>
{% endfor %}
Output
All - All
Asia Pacific - Asia Pacific
Australia - Australia
Queensland - Queensland
New South Wales - New South Wales
I would like to return just one parent based on the depth column in the linking table (regions_tree.depth). Normally, I would use the following SQL to find this parent:
SELECT a.`id`
FROM `regions` AS a
LEFT JOIN `regions_tree` ON `regions_tree`.`parent_id` = a.`id`
LEFT JOIN `regions` AS b ON b.`id` = `regions_tree`.`child_id`
WHERE b.`id` = $child_id AND `regions_tree`.`depth` = 1;
Is there a way of filtering a hasManyToMany()
relationship (preferrably inside initialize()
)? If not, what would be the best way to achieve the following result:
{% for region in regions %}
<p>{{ region.name }} - {{ region.parent.name }}</p>
{% endfor %}
All -
Asia Pacific - All
Australia - Asia Pacific
Queensland - Australia
New South Wales - Australia
Thanks in advance. I appreciate it!