Storing trees in a relational database. Keep in mind the tree needs to have a single root, so it is probably safe to begin with this structure (this example is mySQL, but it should be clear):
CREATE TABLE struct (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
lft int(10) unsigned NOT NULL,
rgt int(10) unsigned NOT NULL,
lvl int(10) unsigned NOT NULL,
pid int(10) unsigned NOT NULL,
pos int(10) unsigned NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO struct VALUES (1, 1, 2, 0, 0, 0);
# now you can use 1 as your tree root
Via Composer
$ composer require vakata/phptree
// create an instance
$dbc = new \vakata\database\DB("mysqli://root@127.0.0.1/treedb");
$tree = new \vakata\phptree\Tree(
$dbc,
'tree_table',
[ 'id' => 'id', 'parent' => 'pid', 'position' => 'pos', 'level' => 'lvl', 'left' => 'lft', 'right' => 'rgt' ]
);
// WORKING WITH NODES
$tree->getRoot()->getChildren(); // get all children of the root
$tree->getRoot()->addChild(new \vakata\phptree\Node(['key' => 'val1'])); // create a node
$tree->getRoot()->addChild(new \vakata\phptree\Node(['key' => 'val2'])); // create a node
$tree->save();
$tree->getNode(2)->moveTo($tree->getRoot(), 2);
$tree->getNode(3)->copyTo($tree->getRoot());
$tree->getNode(3)->remove();
Read more in the API docs
$ composer test
Please see CONTRIBUTING for details.
If you discover any security related issues, please email github@vakata.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.