Finders

Version 2 (Kien La, 2010-06-19 05:40 PM)

1 2 Kien La
*(#topic-list) "Single record result":/projects/main/wiki/Finders#single-record-result
2 2 Kien La
* "Multiple records result":/projects/main/wiki/Finders#multiple-records-result
3 2 Kien La
4 1
h2. Finders
5 1
6 1
ActiveRecord supports a number of methods by which you can find records such as: via primary key, dynamic field name finders. It has the ability to fetch all the records in a table with a simple call, or you can make use of options like order, limit, select, and group.
7 1
8 1
There are essentially two groups of finders you will be working with: a single record result and multiple records result. Sometimes there will be little transparency for the method calls, meaning you may use the same method to get either one, but you will pass an option to that method to signify which type of result you will fetch.
9 1
10 1
All methods used to fetch records from your database will go through *Model::find()*, with one exception, custom sql can be passed to Model::find_by_sql(). In all cases, the finder methods in ActiveRecord are statically invoked. This means you will always use the following type of syntax.
11 1
12 1
<pre class="code"><code class="php">
13 1
class Book extends ActiveRecord\Model {}
14 1
 
15 1
Book::find('all');
16 1
Book::find('last');
17 1
Book::first();
18 1
Book::last();
19 1
Book::all();
20 1
</code></pre>
21 1
 
22 2 Kien La
h4(#single-record-result). Single record result
23 1
24 1
Whenever you invoke a method which produces a single result, that method will return an instance of your model class. There are 3 different ways to fetch a single record result. We'll start with one of the most basic forms.
25 1
26 1
h4. Find by primary key
27 1
28 1
You can grab a record by passing a primary key to the find method. You may pass an options array as the second argument for creating specific queries. If no record is found, a RecordNotFound exception will be thrown.
29 1
30 1
<pre class="code"><code class="php">
31 1
# Grab the book with the primary key of 2
32 1
Book::find(2);
33 1
# sql => SELECT * FROM `books` WHERE id = 2
34 1
</code></pre>
35 1
 
36 1
h4. Find first
37 1
38 1
You can get the first record back from your database two ways. If you do not pass conditions as the second argument, then this method will fetch all the results from your database, but will only return the very first result back to you. Null will be returned if no records are found.
39 1
40 1
<pre class="code"><code class="php">
41 1
# Grab all books, but only return the first result back as your model object.
42 1
$book = Book::first();
43 1
echo "the first id is: {$book->id}" # => the first id is: 1
44 1
# sql => SELECT * FROM `books`
45 1
46 1
# this produces the same sql/result as above
47 1
Book::find('first');
48 1
</code></pre>
49 1
 
50 1
h4. Find last
51 1
52 1
If you haven't yet fallen asleep reading this guide, you should've guessed this is the same as "find first", except that it will return the last result. Null will be returned if no records are found.
53 1
54 1
<pre class="code"><code class="php">
55 1
# Grab all books, but only return the last result back as your model object.
56 1
$book = Book::last();
57 1
echo "the last id is: {$book->id}" # => the last id is: 32
58 1
# sql => SELECT * FROM `books`
59 1
60 1
# this produces the same sql/result as above
61 1
Book::find('last');
62 1
</code></pre>
63 1
 
64 2 Kien La
h4(#multiple-records-result). Multiple records result
65 1
66 1
This type of result will always return an array of model objects. If your table holds no records, or your query yields no results, then an empty array will be given.
67 1
68 1
h4. Find by primary key
69 1
70 1
Just like the single record result for find by primary key, you can pass an array to the find method for multiple primary keys. Again, you may pass an options array as the last argument for creating specific queries. Every key which you use as an argument must produce a corresponding record, otherwise, a RecordNotFound exception will be thrown.
71 1
72 1
<pre class="code"><code class="php">
73 1
# Grab books with the primary key of 2 or 3
74 1
Book::find(2,3);
75 1
# sql => SELECT * FROM `books` WHERE id IN (2,3)
76 1
77 1
# same as above
78 1
Book::find(array(2,3));
79 1
</code></pre>
80 1
 
81 1
h4. Find all
82 1
83 1
There are 2 more ways which you can use to get multiple records back from your database. They use different methods; however, they are basically the same thing. If you do not pass an options array, then it will fetch all records.
84 1
85 1
<pre class="code"><code class="php">
86 1
# Grab all books from the database
87 1
Book::all();
88 1
# sql => SELECT * FROM `books`
89 1
90 1
# same as above
91 1
Book::find('all');
92 1
</code></pre>
93 1
 
94 1
Here we pass some options to the same method so that we don't fetch *every* record.
95 1
96 1
<pre class="code"><code class="php">
97 1
$options = array('limit' => 2);
98 1
Book::all($options);
99 1
# sql => SELECT * FROM `books` LIMIT 0,2
100 1
101 1
# same as above
102 1
Book::find('all', $options);
103 1
</code></pre>
104 1
 
105 1
h4. Finder options
106 1
107 1
There are a number of options available to pass to one of the finder methods for granularity. Let's start with one of the most important options: conditions.
108 1
109 1
h4. Conditions
110 1
111 1
This is the "WHERE" of a SQL statement. By creating conditions, ActiveRecord will parse them into a corresponding "WHERE" SQL statement to filter out your results. Conditions can be extremely simple by only supplying a string. They can also be as complex as you'd like by creating a conditions string that uses ? marks as placeholders for values. Let's start with a simple example of a conditions string.
112 1
113 1
<pre class="code"><code class="php">
114 1
# fetch all the cheap books!
115 1
Book::all(array('conditions' => 'price < 15.00'));
116 1
# sql => SELECT * FROM `books` WHERE price < 15.00
117 1
118 1
# fetch all books that have "war" somewhere in the title
119 1
Book::find(array('conditions' => "title LIKE '%war%'"));
120 1
# sql => SELECT * FROM `books` WHERE title LIKE '%war%'
121 1
</code></pre>
122 1
 
123 1
As stated, you can use *?* marks as placeholders for values which ActiveRecord will replace with your supplied values. The benefit of using this process is that ActiveRecord will escape your string in the backend with your database's native function to prevent SQL injection.
124 1
125 1
<pre class="code"><code class="php">
126 1
# fetch all the cheap books!
127 1
Book::all(array('conditions' => array('price < ?', 15.00)));
128 1
# sql => SELECT * FROM `books` WHERE price < 15.00
129 1
130 1
# fetch all lousy romance novels
131 1
Book::find('all', array('conditions' => array('genre = ?', 'Romance')));
132 1
# sql => SELECT * FROM `books` WHERE genre = 'Romance'
133 1
134 1
# fetch all books with these authors
135 1
Book::find('all', array('conditions' => array('author_id in (?)', array(1,2,3))));
136 1
# sql => SELECT * FROM `books` WHERE author_id in (1,2,3)
137 1
138 1
# fetch all lousy romance novels which are cheap
139 1
Book::all(array('conditions' => array('genre = ? AND price < ?', 'Romance', 15.00)));
140 1
# sql => SELECT * FROM `books` WHERE genre = 'Romance' AND price < 15.00
141 1
</code></pre>
142 1
 
143 1
Here is a more complicated example. Again, the first index of the conditions array are the condition strings. The values in the array after that are the values which replace their corresponding ? marks.
144 1
145 1
<pre class="code"><code class="php">
146 1
# fetch all cheap books by these authors
147 1
$cond =array('conditions'=>array('author_id in(?) AND price < ?', array(1,2,3), 15.00));
148 1
Book::all($cond);
149 1
# sql => SELECT * FROM `books` WHERE author_id in(1,2,3) AND price < 15.00
150 1
</code></pre>
151 1
 
152 1
h4. Limit & Offset
153 1
154 1
This one should be fairly obvious. A limit option will produce a SQL limit clause for supported databases. It can be used in conjunction with the *offset* option.
155 1
156 1
<pre class="code"><code class="php">
157 1
# fetch all but limit to 10 total books
158 1
Book::find('all', array('limit' => 10));
159 1
# sql => SELECT * FROM `books` LIMIT 0,10
160 1
161 1
# fetch all but limit to 10 total books starting at the 6th book
162 1
Book::find('all', array('limit' => 10, 'offset' => 5));
163 1
# sql => SELECT * FROM `books` LIMIT 5,10
164 1
</code></pre>
165 1
 
166 1
h4. Order
167 1
168 1
Produces an ORDERY BY SQL clause.
169 1
170 1
<pre class="code"><code class="php">
171 1
# order all books by title desc
172 1
Book::find('all', array('order' => 'title desc'));
173 1
# sql => SELECT * FROM `books` ORDER BY title desc
174 1
175 1
# order by most expensive and title
176 1
Book::find('all', array('order' => 'price desc, title asc'));
177 1
# sql => SELECT * FROM `books` ORDER BY price desc, title asc
178 1
</code></pre>
179 1
 
180 1
h4. Select
181 1
182 1
Passing a select key in your options array will allow you to specify which columns you want back from the database. This is helpful when you have a table with too many columns, but you might only want 3 columns back for 50 records. It is also helpful when used with a group statement.
183 1
184 1
<pre class="code"><code class="php">
185 1
# fetch all books, but only the id and title columns
186 1
Book::find('all', array('select' => 'id, title'));
187 1
# sql => SELECT id, title FROM `books`
188 1
189 1
# custom sql to feed some report
190 1
Book::find('all', array('select' => 'avg(price) as avg_price, avg(tax) as avg_tax'));
191 1
# sql => SELECT avg(price) as avg_price, avg(tax) as avg_tax FROM `books` LIMIT 5,10
192 1
</code></pre>
193 1
 
194 1
h4. From
195 1
196 1
This designates the table you are selecting from. This can come in handy if you do a join or require finer control.
197 1
198 1
<pre class="code"><code class="php">
199 1
# fetch the first book by aliasing the table name
200 1
Book::first(array('select'=> 'b.*', 'from' => 'books as b'));
201 1
# sql => SELECT b.* FROM books as b LIMIT 0,1
202 1
</code></pre>
203 1
 
204 1
h4. Group
205 1
206 1
Generate a GROUP BY clause.
207 1
208 1
<pre class="code"><code class="php">
209 1
# group all books by prices
210 1
Book::all(array('group' => 'price'));
211 1
# sql => SELECT * FROM `books` GROUP BY price
212 1
</code></pre>
213 1
 
214 1
h4. Having
215 1
216 1
Generate a HAVING clause to add conditions to your GROUP BY.
217 1
218 1
<pre class="code"><code class="php">
219 1
# group all books by prices greater than $45
220 1
Book::all(array('group' => 'price', 'having' => 'price > 45.00'));
221 1
# sql => SELECT * FROM `books` GROUP BY price HAVING price > 45.00
222 1
</code></pre>
223 1
 
224 1
h4. Readonly
225 1
226 1
Readonly models are just that: readonly. If you try to save a readonly model, then a ReadOnlyException will be thrown.
227 1
228 1
<pre class="code"><code class="php">
229 1
# specify the object is readonly and cannot be saved
230 1
$book = Book::first(array('readonly' => true));
231 1
 
232 1
try {
233 1
  $book->save();
234 1
} catch (ActiveRecord\ReadOnlyException $e) {
235 1
  echo $e->getMessage();
236 1
  # => Book::save() cannot be invoked because this model is set to read only
237 1
}
238 1
</code></pre>
239 1
 
240 1
h4. Dynamic finders
241 1
242 1
These offer a quick and easy way to construct conditions without having to pass in a bloated array option. This option makes use of PHP 5.3's "late static binding":http://www.php.net/lsb combined with "__callStatic()":http://www.php.net/__callstatic allowing you to invoke undefined static methods on your model. You can either use YourModel::find_by which returns a single model result and YourModel::find_all_by returns multiple records result. All you have to do is add an underscore and another field name after either of those two methods. Let's take a look.
243 1
244 1
<pre class="code"><code class="php">
245 1
# find a single book by the title of War and Peace
246 1
$book = Book::find_by_title('War and Peace');
247 1
#sql => SELECT * FROM `books` WHERE title = 'War and Peace'
248 1
249 1
# find all discounted books
250 1
$book = Book::find_all_by_discounted(1);
251 1
#sql => SELECT * FROM `books` WHERE discounted = 1
252 1
253 1
# find all discounted books by given author
254 1
$book = Book::find_all_by_discounted_and_author_id(1, 5);
255 1
#sql => SELECT * FROM `books` WHERE discounted = 1 AND author_id = 5
256 1
257 1
# find all discounted books or those which cost 5 bux
258 1
$book = Book::find_by_discounted_or_price(1, 5.00);
259 1
#sql => SELECT * FROM `books` WHERE discounted = 1 OR price = 5.00
260 1
</code></pre>
261 1
 
262 1
h4. Joins
263 1
264 1
A join option may be passed to specify SQL JOINS. There are two ways to produce a JOIN. You may pass custom SQL to perform a join as a simple string. By default, the joins option will not select the attributes from the joined table; instead, it will only select the attributes from your model's table. You can pass a select option to specify the fields.
265 1
266 1
<pre class="code"><code class="php">
267 1
# fetch all books joining their corresponding authors
268 1
$join = 'LEFT JOIN authors a ON(books.author_id = a.author_id)';
269 1
$book = Book::all(array('joins' => $join));
270 1
# sql => SELECT `books`.* FROM `books`
271 1
#	  LEFT JOIN authors a ON(books.author_id = a.author_id)
272 1
</code></pre>
273 1
 
274 1
Or, you may specify a join via an associated model.
275 1
276 1
<pre class="code"><code class="php">
277 1
class Book extends ActiveRecord\Model
278 1
{
279 1
  static $belongs_to = array(array('author'),array('publisher'));
280 1
}
281 1
 
282 1
# fetch all books joining their corresponding author
283 1
$book = Book::all(array('joins' => array('author')));
284 1
# sql => SELECT `books`.* FROM `books`
285 1
#	  INNER JOIN `authors` ON(`books`.author_id = `authors`.id)
286 1
287 1
# here's a compound join
288 1
$book = Book::all(array('joins' => array('author', 'publisher')));
289 1
# sql => SELECT `books`.* FROM `books`
290 1
#	  INNER JOIN `authors` ON(`books`.author_id = `authors`.id)
291 1
#         INNER JOIN `publishers` ON(`books`.publisher_id = `publishers`.id)
292 1
</code></pre>
293 1
 
294 1
Joins can be combined with strings and associated models.
295 1
296 1
<pre class="code"><code class="php">
297 1
class Book extends ActiveRecord\Model
298 1
{
299 1
  static $belongs_to = array(array('publisher'));
300 1
}
301 1
 
302 1
$join = 'LEFT JOIN authors a ON(books.author_id = a.author_id)';
303 1
# here we use our $join string and the association publisher
304 1
$book = Book::all(array('joins' => $join, 'publisher'));
305 1
# sql => SELECT `books`.* FROM `books`
306 1
#	  LEFT JOIN authors a ON(books.author_id = a.author_id)
307 1
#         INNER JOIN `publishers` ON(`books`.publisher_id = `publishers`.id)
308 1
</code></pre>
309 1
 
310 1
h4. Find by custom SQL
311 1
312 1
If, for some reason, you need to create a complicated SQL query beyond the capacity of finder options, then you can pass a custom SQL query through Model::find_by_sql(). This will render your model as readonly so that you cannot use any write methods on your returned model(s).
313 1
314 1
*Caution:* find_by_sql() will NOT prevent SQL injection like all other finder methods. The burden to secure your custom find_by_sql() query is on you.
315 1
316 1
<pre class="code"><code class="php">
317 1
# this will return a single result of a book model with only the title as an attirubte
318 1
$book = Book::find_by_sql('select title from `books`');
319 1
 
320 1
# you can even select from another table
321 1
$cached_book = Book::find_by_sql('select * from books_cache');
322 1
# this will give you the attributes from the books_cache table
323 1
</code></pre>