Aliasing

Normally, a property that contains a bean needs to be named after it's type. We have seen this with parent objects; to access the village a building belongs to, you just read the


    $building
->village     
property. 90% of the time this is exactly what you need. A parent object can be aliased though.

When dealing with people you often have to store persons using a role name. For instance, two people are working on a science project. Both people are in fact 'person' beans. However one of them is a teacher and the other is a student.


    
list($teacher,$student) = R::dispense('person',2);
    
$project->student $student
    
$project->teacher $teacher

RedBeanPHP will store both the student and the teacher as persons because RedBeanPHP simply ignores the property name when saving. RedBeanPHP stores the student and the teacher both as person beans and the project table will get two fields: teacher_id and student_id pointing to the respective person records. However when you retrieve the project from the database, you need to to tell RedBeanPHP that a student or teacher is in fact a person. To do so, you have to use the fetchAs() function:


    $teacher 
$project->fetchAs('person')->teacher;

Aliased Lists (3.3+)

To get a list of all projects associated with a certain person, in the role of a student (aliased as student) use:


    $person
->alias('student')->ownProject;

Although RedBeanPHP supports aliasing and therefore custom column mapping, I believe that any well designed application does not need this feature. Many aliased relations can be solved using an intermediate bean; for instance in our teacher/student example we could simply use a participant bean and a role property that can be either 'student' or 'teacher'. Also note that some powerful RedBeanPHP functions do not support aliased properties; most notably R::dependencies() and R::exportAll().

Aliased lists have been added in version 3.3

In other words…

Aliasing is the RedBeanPHP way of saying 'one-to-X'.


 
 

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