Relationships
Prev Chapter 13. Relationships Between Models Next

Relationships

A Post belongs to a User and has many Tags. Lets take another look at how this is represented using annotations:

Example 13.4.  !HasMany and !BelongsTo on a Post

<?php
/**
 * !BelongsTo user, Key: authorId
 * !HasMany tags, Through: PostTag
 */
class Post extends Model { /** Stripped for Brevity */ }
?>

The !BelongsTo annotation denotes the 'one' side of a one-to-many relationship. We specify some additional information using the Key modifier to say that the foreign key column name is actually authorId instead of userId which is what it would be by convention. With a belongs to relationship Post has an attached method of user() which will return the User model a Post is associated with. It also adds attached methods for setting and unsetting the user: setUser($user) unsetUser(). Attached methods are a low-level feature of Recess written in Object which allow methods to be added to classes dynamically at run time.

The !HasMany annotation is a special variant of !HasMany because it uses the Through modifier. This tells the HasMany relationship to use a join table thus making it a many-to-many relationship instead of a one-to-many. The !HasMany annotation attaches the following methods to the Post class: tags() , addToTags($tag), and removeFromTags($tag).


Prev Up Next
Chapter 13. Relationships Between Models Home Naming Conventions