Associations

From RedBean

Jump to: navigation, search

Contents

Associations

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' );

N:1 Relations

As you see RedBean does not have a way to store N:1 relations (actually it has, see Advanced Associations but we pretend it does'nt), this is because the concept of a schema constraint is incompatible with RedBean. In RedBean all code is *equal*, meaning that one piece of code may not restrict the power of another piece of code. N:1 relationships in RedBean are a matter of perception. If your code wants to 'assume' that a book has only one cover, it just fetches the first cover it can find.

R::relatedOne( $book, 'cover' );

The proper way to change to cover of a book is:

R::clearRelations( $book, 'cover' );
R::associate( $book, $cover );

Because this is a bit cumbersome, RedBean offers a more convenient way:

R::clearRelations( $book, 'cover', $cover);

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"  ');

For more complex associations: Advanced Associations

Personal tools