Chapter 13. Relationships Between Models
Prev Part III. The Recess Framework Next

Chapter 13. Relationships Between Models

Table of Contents

A Preview
Relationships
Naming Conventions

A Preview

Lets say we need a controller method that is given a user $id and $keyword. The method will find the tags of all posts whose title contains $keyword that was written by the user with id of $id.

Example 13.1. Querying across relationships

<?php
/** !Route GET, user/$id/keyword/$keyword/tags */
function getTagsForUserByPostTitleKeyword($id, $keyword) {
    $this->user = new User($id);
    $this->tags = $user
                    ->posts()
                    ->like('title',"%$keyword%")
                    ->tags();
}

In a view we can iterate through the tags with a simple foreach:

Example 13.2. Iterating through a query's results

<?php
foreach($tags as $tag) {
    echo $tag->name, '<br />';
}

Now, let's look at the code for the User, Post, and Tag models that make the above code snippet possible.

Example 13.3. Relationships between classes

<?php
/** !HasMany posts */
class User extends Model { }

/** 
 * !BelongsTo user
 * !HasMany tags, Through: PostsTags
 */
class Post extends Model { }

/**
 * !HasMany posts, Through: PostsTags
 */
class Tag extends Model { }

/**
 * This model represents the join table between the many-to-many
 * Posts <-> Tags relationship.
 *
 * !BelongsTo post
 * !BelongsTo tag
 */
class PostsTags extends Model { }


Prev Up Next
Persisting Model state with insert , update , save , delete  Home Relationships