RedBeanPHP 4KS
Easy ORM for PHP


RedBeanPHP also supports self-referential one-to-many and many-to-many relationships. In RedBeanPHP terminology these are called trees. Here is an example, let's decorate a christmas tree with some candy canes:

    $cane R::dispense('cane',10);
$cane[1]->ownCane = array( $cane[2], $cane[9] );
$cane[2]->ownCane = array( $cane[3], $cane[4] );
$cane[4]->ownCane = array( $cane[5], 
$cane[7], $cane[8] );
$cane[5]->ownCane = array( $cane[6] );
$id R::store($cane[1]);
$root R::load('cane',$id);
//outputs: 6

In fact trees are just a special case of lists.


Instead of manually looping through each own-list of a bean you can simply use the traverse() method:

    $page->traverse'ownPage', function( $page ) {
    } );

This allows you to recursively apply a function to a list. To limit the results when accessing a list you can use the with/withCondition() method:

    $page->with' LIMIT 10 ')->traverse( ... );
$page->withCondition'  rating > ? ', [ ] )->traverse( ... );

You can also use withCondition and alias together with the traverse function. Use the third parameter to specify the maximum depth:

    $page->traverse'ownPage'$func); //max 3 levels

Use the PHP use statement to import variables into the functions scope:

    $task->traverse'ownTask', function( $task ) use ( &$todos ) {
$todos[] = $task->name;    
    } );    

The traverse() function does not check for recursion in trees.


RedBeanPHP Easy ORM for PHP © 2014 Gabor de Mooij () and the RedBeanPHP community (credits) - Licensed New BSD/GPLv2 - RedBeanPHP Archives