Querying Models
Prev Chapter 12. Models Next

Querying Models

Queries are constructed using a simple API. They're also lazy so queries are not executed until you need the results. The following are some example queries we could perform with the Post model:

Example 12.2.  Querying the Post Model

<?php

$post = new Post();

$allPosts = $post->all(); // Select all Posts

$postsWithPhp = $allPosts->like('title', '%PHP%');

$lastFivePhpPosts = $postsWithPhp->orderBy('id DESC')->limit(5);
// Logically equivalent to:
$lastFivePhpPosts = $allPosts
                        ->orderBy('id DESC')
                        ->limit(5)
                        ->like('title', '%PHP%');

$postWithAuthorId5 = $post->equal('authorId', 5);

The all() method is essentially a SELECT * on Post 's table. Notice how we can take the result of all() and continue refining our query with a LIKE clause on line 3. As mentioned above, Recess Models use lazy evaluation. The code above would not issue any SQL queries unless later in code the results were accessed in a foreach loop or with the array index syntax (i.e. $postsWithAuthorId[0] ). Other simple query operators include: notEqual , between , greaterThan , greaterThanOrEqualTo , lessThan , lessThanOrEqualTo , notLike .


Prev Up Next
Chapter 12. Models Home  Persisting Model state with insert , update , save , delete