RedBeanPHP 4
The Power ORM

Trees

RedBeanPHP supports self-referential 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);

    echo 
$root->ownCane[2]->ownCane[4]
        ->
ownCane[5]->ownCane[6]->id;
    
//outputs: 6

Trees are just a special case of lists, you use a list with the same name as the parent type. In the example script above, a cane has an ownCaneList. Another example: page->ownPageList. As you can see in the example above you can navigate the lists using the IDs.

Traversal

Instead of manually looping through each own-list of a bean you can 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 function 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 () and the RedBeanPHP community () - Licensed New BSD/GPLv2 - RedBeanPHP Archives