RedBeanPHP

easy ORM for PHP

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 which is useful in more complex relations.

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. The person thus has ownProject, but two persons can share a project because they have a different role; i.e. teacher and 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. The columns teacher_id and student_id will be used just as you expect. 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;

Note that $person->ownProject will not work in this case, you will have to find them using
R::find('project',' teacher_id = ? ...



User contributed notes. Please use the comment section to provide tips, notes and examples. To ask for support or to provide feedback use the forum. For bug reports use Github Issue Tracker.

Site comments powered by Disqus

page generated in 0.010724067687988 sec.