Hello readers, today we discuss about "Tree Structure (or hierarchical data) in cakephp".
It can fairly common to want to maintain hierarchical data in a database stand. Examples of such data might be categories with unlimited subcategories, data related to a multilevel menu system or a textual representation of hierarchy such as can be used to maintain access control objects with ACL logic.
For small trees of data, or the place that the data is merely a few levels deep it is straightforward to add a parent_id field to your database table and use this to keep monitor of which item is the parent of what. Bundled with cake however, is an effective behavior which allows you to use the great things about MPTT (modified preorder tree traversal) reason without having to be concerned about any of the intricacies of the approach - until you want to.
To work with the shrub behavior, your database desk needs 3 fields as listed below (all are ints):
1. parent - arrears fieldname is parent_id, to store the id of the parent object
2. left - default fieldname is lft, to store the lft value of the current row.
3. right - default fieldname is rght, to store the rght value of the present strip.
If you are habitual with Modified Preorder Tree Traversal logic you may fascinate why a parent field exists , it's better to do certain tasks if a direct parent hyperlink is stored on the database - such as finding direct children.
You can use the below code for better understanding.
Example:
<!-- creating table categories -->
CREATE TABLE categories (
id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INTEGER(10) DEFAULT PRIMARY KEY NULL,
left INTEGER(10) DEFAULT NULL,
rght INTEGER(10) DEFAULT NULL,
name VARCHAR(255) DEFAULT
);
Inserting data in table categories:
INSERT INTO 'categories' ('id', 'name', 'parent_id', 'left', 'rght') VALUES (1, 'Sports', NULL, 1, 30), (2, 'Cricket', 1, 2, 15), (3, 'ODI', 2, 3, 8), (4, '50-50 ODI', 3, 4, 5), (5, '20-20 ODI', 3, 6, 7), (6, 'Test Match', 2, 9, 14), (9, 'Football', 1, 16, 29), (10, 'Real Madrid', 9, 17, 22), (11, 'Ronaldo', 10, 18, 19), (13, 'Barcelona', 9, 23, 28), (14, 'Messi', 13, 24, 25), (15, 'Neymar', 13, 26, 27);
use this code into yourcontroller
$treelist = $this->Category->generateTreeList();
The hierarchical data come in the form of array like below.
array(
[1] => "Sports",
[2] => "_Cricket",
[3] => "__ODI",
[4] => "___50-50 ODI",
[5] => "___20-20 ODI",
[6] => "__Test Match",
[7] => "_Football",
[8] => "__Real Madrid",
[9] => "___Ronaldo",
[10] => "__Barcelona",
[11] => "___Messi"
)
0 Comment(s)