- Getting started
- Basics
- Finding
- Relation Mapping
- Models
- Database
- BeanCan
- Advanced
- Custom getters
- Association API
- Copy Beans
- Tags
- Import and Export
- Debug
- Meta Data
- Architecture
- Other
Association API
Another way to use many-to-many relations is to use the R::associate() function. This function takes two beans and associates them. To get all beans related to a certain bean you can use its counterpart R::related().
R::associate( $book, $page );
R::related( $page, 'book' );
R::relatedOne( $page, 'book'); //just the first bean
To break the association between the two:
R::unassociate( $book, $page );
To unassociate all related beans:
R::clearRelations( $book, 'page' );
Sometimes you want to know which beans aren't associated with a certain bean:
R::unrelated( $scandal, 'politician', $sql, $values );
Are Related
To find out whether two specific beans are related, use the R::areRelated() function.
R::areRelated( $husband, $wife );
This function returns TRUE if the two beans have been associated using a many-to-many relation (associate) and FALSE otherwise.
Complete Guide
Igor Couto has written an full guide on how to use beans to establish all sorts of database relations. I believe this guide is an excellent resource for everyone working with RedBeanPHP. Among other subjects this guide discusses simple relationships, one-to-many, many-to-many, one-to-one, self-referential, poly-one, poly-many etc. Feel free to contribute. Besides the PDF, there is also a pages edition and a MS Word edition.
Association and SQL
With the Association API it's possible to include some SQL in your relational query:
R::related( $album, 'track', ' length > ? ', array($seconds) );
Extended Associations
An extended association is a many-to-many association with some extra information.
R::associate($track,$album,array('sequencenumber'=>$s));
JSON is also allowed:
R::associate($track,$album,'{"order":"2"}');
Or just a string:
R::associate($track,$album,'2'); //stored in property 'extra'
To load a association link:
$keys = R::$extAssocManager->related($album,'track');
Tweet
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