Relations
From RedBean
Contents |
Relations
RedBean has an incredibly simple system for managing relations among beans. This is best explained by using an example. For instance, imagine we have a bean of type 'book' and we have beans of type 'page'. To put a page in our book we say:
R::associate( $book, $page );
To get all the pages that are part of the book:
R::related( $page, 'book' ); //or.. R::related( $book, 'page' );
To tear a page out of the book:
R::unassociate( $book, $page ); //or $page $book
To tear all the pages out of the book:
R::clearRelations( $book, 'page' );
Or to tear this page out of all books:
R::clearRelations( $page, 'book' );
relatedOne
To find only the first/one related cover
R::relatedOne( $book, 'cover' );
To change to cover of a book:
R::clearRelations( $book, 'cover' ); R::associate( $book, $cover );
Or using a shortcut:
R::clearRelations( $book, 'cover', $cover);
Views (since RedBean 2.0)
Want to fetch all related items at once? Use a view:
R::view('library', 'page,book,author');
You can now query a view called library that has all the information about all pages, books and authors. For instance, to get all pages written by author 'Homerus':
R::getAll('select bodytext from library where name_of_author = ? ', array('Homerus'));
Note that to reference a property originally belonging to another table (name) use: (PROPERTY)_of_(TABLE).
N:1 Relations
RedBeanPHP offers no special functionality to handle N:1 relations, but using foreign key or N:1 associations manually is easy:
$page->book_id = $page->id
And loading a foreign key association is also a no-brainer:
$pages = R::find("page"," book_id = ? ",array($book->id));
Or the other way around:
$book = R::load("book", $page->id );
Unrelated
To find out which beans are NOT related to a specific bean you can use:
R::unrelated( $scandal, "politician", $sql, $values );
This query will find out for you what politicians have not been involved in the given scandal.
Using Additional SQL
This example demonstrates the use of additional SQL:
$track->orderNum = 1; R::associate( $album, $track ); //In case you have no WHERE clause, start with 1 R::related( $album, 'track', ' 1 ORDER BY orderNum ' );
$t = R::dispense('person');
$s = R::dispense('person');
$t->role = 'teacher';
$s->role = 'student';
R::associate($t, $s);
R::related($t, 'person', ' role = "student" ');
You can also use bindings:
R::related( $album, 'track', ' length > ? ', array($seconds) );
And this works with R::relatedOne as well...
R::relatedOne( $album, 'track', ' length > ? ', array($seconds) );
Read more about Associations,Advanced Associations.

