This manual has been archived. Visit the new manual here.
RedBeanPHP
 

Shared Lists

Consider the following example concerning a strategy game: An army can defend one or more villages. Thus an army can belong to many villages, or do the villages belong to the army? In any case, this is an example of a many-to-many relationship. Many villages can be associated with many armies. In RedBeanPHP we describe this kind of relation with a shared-list.


    $army 
R::dispense('army');
    
$village->sharedArmy[] = $army;
    
$village2->sharedArmy[] = $army;

Now both villages have the same army. Once again the name of the shared list property needs to match the type of bean it stores. In the database, RedBeanPHP will make a link table army_village to associate the armies with their villages.

The other end of the beans…

Which villages does an army belong to? To answer this question use:


    $myVillages 
$army->sharedVillage;
    
//or.. R::related($army,'village');

For the rest, shared lists work just like own-lists.

Additional properties (3.4)

To add additional properties to a relation you can add the shared beans using the link() method like this:


    $village
->link('army_village',
        array(
'action'=>'defend'))->army $army1;

Instead of an array you may also use a JSON string:


    $village
->link('army_village',
        
'{"action":"defend"}')->army $army1;

Personally I prefer to rename such relations:


    R
::renameAssociation('army_village','visit');
    
    
$village->link('visit',
        
'{"action":"defend"}')->army $army1;
    
    
R::store($village);
    
    
//returns armies linked in visit table
    
$armies $village->sharedArmies;

In other words…

Shared lists are the RedBeanPHP way of saying: 'many-to-many'.


 
 

RedBeanPHP Easy ORM for PHP © 2013 Gabor de Mooij and the RedBeanPHP community - Licensed New BSD/GPLv2